home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / BARNET / ARMTEX / SOURCES2 / !TeX / texmf / source / armTeX / TeX / tex / web (.txt)
Encoding:
Texinfo Document  |  1994-02-01  |  1004.4 KB  |  21,444 lines

  1. % This program is copyright (C) 1982 by D. E. Knuth; all rights are reserved.
  2. % Copying of this file is authorized only if (1) you are D. E. Knuth, or if
  3. % (2) you make absolutely no changes to your copy. (The WEB system provides
  4. % for alterations via an auxiliary file; the master file should stay intact.)
  5. % See Appendix H of the WEB manual for hints on how to install this program.
  6. % And see Appendix A of the TRIP manual for details about how to validate it.
  7. % TeX is a trademark of the American Mathematical Society.
  8. % METAFONT is a trademark of Addison-Wesley Publishing Company.
  9. % Version 0 was released in September 1982 after it passed a variety of tests.
  10. % Version 1 was released in November 1983 after thorough testing.
  11. % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
  12. % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
  13. % Version 1.3 made memory allocation more flexible and local (November 1984).
  14. % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
  15. % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
  16. % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
  17. % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
  18. % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
  19. % Version 2.3 avoided incomplete page in premature termination (August 1987).
  20. % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
  21. % Version 2.5 saved cur_order when expanding tokens (September 1987).
  22. % Version 2.6 added 10sp slop when shipping leaders (November 1987).
  23. % Version 2.7 improved rounding of negative-width characters (November 1987).
  24. % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
  25. % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
  26. % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
  27. % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
  28. % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
  29. % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
  30. % Version 2.95 solved that problem a better way (December 1988).
  31. % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
  32. % Version 2.97 corrected blunder in creating 2.95 (February 1989).
  33. % Version 2.98 omitted save_for_after at outer level (March 1989).
  34. % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
  35. % Version 2.991 caught .5\ifdim.6... (June 1989).
  36. % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
  37. % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
  38. % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
  39. % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
  40. % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
  41. % Version 3.141 more of same; reconstituted ligatures better (March 1992).
  42. % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
  43. % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
  44. % A reward of $327.68 will be paid to the first finder of any remaining bug,
  45. % not counting changes introduced after August 1989.
  46. % Although considerable effort has been expended to make the TeX program
  47. % correct and reliable, no warranty is implied; the author disclaims any
  48. % obligation or liability for damages, including but not limited to
  49. % special, indirect, or consequential damages arising out of or in
  50. % connection with the use or performance of this software. This work has
  51. % been a ``labor of love'' and the author hopes that users enjoy it.
  52. % Here is TeX material that gets inserted after \input webmac
  53. \def\hang{\hangindent 3em\noindent\ignorespaces}
  54. \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
  55. \font\ninerm=cmr9
  56. \let\mc=\ninerm % medium caps for names like SAIL
  57. \def\PASCAL{Pascal}
  58. \def\ph{\hbox{Pascal-H}}
  59. \def\pct!{{\char`\%}} % percent sign in ordinary text
  60. \font\logo=logo10 % font used for the METAFONT logo
  61. \def\MF{{\logo META}\-{\logo FONT}}
  62. \def\<#1>{$\langle#1\rangle$}
  63. \def\section{\mathhexbox278}
  64. \def\(#1){} % this is used to make section names sort themselves better
  65. \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
  66. \outer\def\N#1. \[#2]#3.{\MN#1.\vfil\eject % begin starred section
  67.   \def\rhead{PART #2:\uppercase{#3}} % define running headline
  68.   \message{*\modno} % progress report
  69.   \edef\next{\write\cont{\Z{\?#2]#3}{\modno}{\the\pageno}}}\next
  70.   \ifon\startsection{\bf\ignorespaces#3.\quad}\ignorespaces}
  71. \let\?=\relax % we want to be able to \write a \?
  72. \def\title{\TeX82}
  73. \def\topofcontents{\hsize 5.5in
  74.   \vglue 0pt plus 1fil minus 1.5in
  75.   \def\?##1]{\hbox to 1in{\hfil##1.\ }}
  76. \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
  77. \pageno=3
  78. \def\glob{13} % this should be the section number of "<Global...>"
  79. \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
  80. @* \[1] Introduction.
  81. This is \TeX, a document compiler intended to produce typesetting of high
  82. quality.
  83. The \PASCAL\ program that follows is the definition of \TeX82, a standard
  84. @:PASCAL}{\PASCAL@>
  85. @!@:TeX82}{\TeX82@>
  86. version of \TeX\ that is designed to be highly portable so that identical output
  87. will be obtainable on a great variety of computers.
  88. The main purpose of the following program is to explain the algorithms of \TeX\
  89. as clearly as possible. As a result, the program will not necessarily be very
  90. efficient when a particular \PASCAL\ compiler has translated it into a
  91. particular machine language. However, the program has been written so that it
  92. can be tuned to run efficiently in a wide variety of operating environments
  93. by making comparatively few changes. Such flexibility is possible because
  94. the documentation that follows is written in the \.{WEB} language, which is
  95. at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
  96. to \PASCAL\ is able to introduce most of the necessary refinements.
  97. Semi-automatic translation to other languages is also feasible, because the
  98. program below does not make extensive use of features that are peculiar to
  99. \PASCAL.
  100. A large piece of software like \TeX\ has inherent complexity that cannot
  101. be reduced below a certain level of difficulty, although each individual
  102. part is fairly simple by itself. The \.{WEB} language is intended to make
  103. the algorithms as readable as possible, by reflecting the way the
  104. individual program pieces fit together and by providing the
  105. cross-references that connect different parts. Detailed comments about
  106. what is going on, and about why things were done in certain ways, have
  107. been liberally sprinkled throughout the program.  These comments explain
  108. features of the implementation, but they rarely attempt to explain the
  109. \TeX\ language itself, since the reader is supposed to be familiar with
  110. {\sl The \TeX book}.
  111. @.WEB@>
  112. @:TeXbook}{\sl The \TeX book@>
  113. @ The present implementation has a long ancestry, beginning in the summer
  114. of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
  115. a prototype
  116. @^Plass, Michael Frederick@>
  117. @^Liang, Franklin Mark@>
  118. @^Knuth, Donald Ervin@>
  119. based on some specifications that the author had made in May of that year.
  120. This original proto\TeX\ included macro definitions and elementary
  121. manipulations on boxes and glue, but it did not have line-breaking,
  122. page-breaking, mathematical formulas, alignment routines, error recovery,
  123. or the present semantic nest; furthermore,
  124. it used character lists instead of token lists, so that a control sequence
  125. like \.{\\halign} was represented by a list of seven characters. A
  126. complete version of \TeX\ was designed and coded by the author in late
  127. 1977 and early 1978; that program, like its prototype, was written in the
  128. {\mc SAIL} language, for which an excellent debugging system was
  129. available. Preliminary plans to convert the {\mc SAIL} code into a form
  130. somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
  131. the author at the beginning of 1979, and a complete implementation was
  132. created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
  133. @^Zabala Salelles, Ignacio Andres@>
  134. was written by the author during the latter part of 1981 and the early
  135. part of 1982, also incorporates ideas from the 1979 implementation of
  136. @^Guibas, Leonidas Ioannis@>
  137. @^Sedgewick, Robert@>
  138. @^Wyatt, Douglas Kirk@>
  139. \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
  140. and Douglas Wyatt at the Xerox Palo Alto Research Center.  Several hundred
  141. refinements were introduced into \TeX82 based on the experiences gained with
  142. the original implementations, so that essentially every part of the system
  143. has been substantially improved. After the appearance of ``Version 0'' in
  144. September 1982, this program benefited greatly from the comments of
  145. many other people, notably David~R. Fuchs and Howard~W. Trickey.
  146. A final revision in September 1989 extended the input character set to
  147. eight-bit codes and introduced the ability to hyphenate words from
  148. different languages, based on some ideas of Michael~J. Ferguson.
  149. @^Fuchs, David Raymond@>
  150. @^Trickey, Howard Wellington@>
  151. @^Ferguson, Michael John@>
  152. No doubt there still is plenty of room for improvement, but the author
  153. is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
  154. and reliability are to be its main virtues.
  155. On the other hand, the \.{WEB} description can be extended without changing
  156. the core of \TeX82 itself, and the program has been designed so that such
  157. extensions are not extremely difficult to make.
  158. The |banner| string defined here should be changed whenever \TeX\
  159. undergoes any modifications, so that it will be clear which version of
  160. \TeX\ might be the guilty party when a problem arises.
  161. @^extensions to \TeX@>
  162. @^system dependencies@>
  163. If this program is changed, the resulting system should not be called
  164. `\TeX'; the official name `\TeX' by itself is reserved
  165. for software systems that are fully compatible with each other.
  166. A special test suite called the ``\.{TRIP} test'' is available for
  167. helping to determine whether a particular implementation deserves to be
  168. known as `\TeX' [cf.~Stanford Computer Science report CS1027,
  169. November 1984].
  170. @d banner=='This is TeX, Version 3.14159' {printed when \TeX\ starts}
  171. @ Different \PASCAL s have slightly different conventions, and the present
  172. @!@:PASCAL H}{\ph@>
  173. program expresses \TeX\ in terms of the \PASCAL\ that was
  174. available to the author in 1982. Constructions that apply to
  175. this particular compiler, which we shall call \ph, should help the
  176. reader see how to make an appropriate interface for other systems
  177. if necessary. (\ph\ is Charles Hedrick's modification of a compiler
  178. @^Hedrick, Charles Locke@>
  179. for the DECsystem-10 that was originally developed at the University of
  180. Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
  181. 29--42. The \TeX\ program below is intended to be adaptable, without
  182. extensive changes, to most other versions of \PASCAL, so it does not fully
  183. use the admirable features of \ph. Indeed, a conscious effort has been
  184. made here to avoid using several idiosyncratic features of standard
  185. \PASCAL\ itself, so that most of the code can be translated mechanically
  186. into other high-level languages. For example, the `\&{with}' and `\\{new}'
  187. features are not used, nor are pointer types, set types, or enumerated
  188. scalar types; there are no `\&{var}' parameters, except in the case of files;
  189. there are no tag fields on variant records; there are no assignments
  190. |real:=integer|; no procedures are declared local to other procedures.)
  191. The portions of this program that involve system-dependent code, where
  192. changes might be necessary because of differences between \PASCAL\ compilers
  193. and/or differences between
  194. operating systems, can be identified by looking at the sections whose
  195. numbers are listed under `system dependencies' in the index. Furthermore,
  196. the index entries for `dirty \PASCAL' list all places where the restrictions
  197. of \PASCAL\ have not been followed perfectly, for one reason or another.
  198. @!@^system dependencies@>
  199. @!@^dirty \PASCAL@>
  200. @ The program begins with a normal \PASCAL\ program heading, whose
  201. components will be filled in later, using the conventions of \.{WEB}.
  202. @.WEB@>
  203. For example, the portion of the program called `\X\glob:Global
  204. variables\X' below will be replaced by a sequence of variable declarations
  205. that starts in $\section\glob$ of this documentation. In this way, we are able
  206. to define each individual global variable when we are prepared to
  207. understand what it means; we do not have to define all of the globals at
  208. once.  Cross references in $\section\glob$, where it says ``See also
  209. sections \gglob, \dots,'' also make it possible to look at the set of
  210. all global variables, if desired.  Similar remarks apply to the other
  211. portions of the program heading.
  212. Actually the heading shown here is not quite normal: The |program| line
  213. does not mention any |output| file, because \ph\ would ask the \TeX\ user
  214. to specify a file name if |output| were specified here.
  215. @^system dependencies@>
  216. @d mtype==t@&y@&p@&e {this is a \.{WEB} coding trick:}
  217. @f mtype==type {`\&{mtype}' will be equivalent to `\&{type}'}
  218. @f type==true {but `|type|' will not be treated as a reserved word}
  219. @p @t\4@>@<Compiler directives@>@/
  220. program TEX; {all file names are defined dynamically}
  221. label @<Labels in the outer block@>@/
  222. const @<Constants in the outer block@>@/
  223. mtype @<Types in the outer block@>@/
  224. var @<Global variables@>@/
  225. procedure initialize; {this procedure gets things started properly}
  226.   var @<Local variables for initialization@>@/
  227.   begin @<Initialize whatever \TeX\ might access@>@;
  228.   end;@#
  229. @t\4@>@<Basic printing procedures@>@/
  230. @t\4@>@<Error handling procedures@>@/
  231. @ The overall \TeX\ program begins with the heading just shown, after which
  232. comes a bunch of procedure declarations and function declarations.
  233. Finally we will get to the main program, which begins with the
  234. comment `|start_here|'. If you want to skip down to the
  235. main program now, you can look up `|start_here|' in the index.
  236. But the author suggests that the best way to understand this program
  237. is to follow pretty much the order of \TeX's components as they appear in the
  238. \.{WEB} description you are now reading, since the present ordering is
  239. intended to combine the advantages of the ``bottom up'' and ``top down''
  240. approaches to the problem of understanding a somewhat complicated system.
  241. @ Three labels must be declared in the main program, so we give them
  242. symbolic names.
  243. @d start_of_TEX=1 {go here when \TeX's variables are initialized}
  244. @d end_of_TEX=9998 {go here to close files and terminate gracefully}
  245. @d final_end=9999 {this label marks the ending of the program}
  246. @<Labels in the out...@>=
  247. start_of_TEX@t\hskip-2pt@>, end_of_TEX@t\hskip-2pt@>,@,final_end;
  248.   {key control points}
  249. @ Some of the code below is intended to be used only when diagnosing the
  250. strange behavior that sometimes occurs when \TeX\ is being installed or
  251. when system wizards are fooling around with \TeX\ without quite knowing
  252. what they are doing. Such code will not normally be compiled; it is
  253. delimited by the codewords `$|debug|\ldots|gubed|$', with apologies
  254. to people who wish to preserve the purity of English.
  255. Similarly, there is some conditional code delimited by
  256. `$|stat|\ldots|tats|$' that is intended for use when statistics are to be
  257. kept about \TeX's memory usage.  The |stat| $\ldots$ |tats| code also
  258. implements diagnostic information for \.{\\tracingparagraphs} and
  259. \.{\\tracingpages}.
  260. @^debugging@>
  261. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  262. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  263. @f debug==begin
  264. @f gubed==end
  265. @d stat==@{ {change this to `$\\{stat}\equiv\null$' when gathering
  266.   usage statistics}
  267. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$' when gathering
  268.   usage statistics}
  269. @f stat==begin
  270. @f tats==end
  271. @ This program has two important variations: (1) There is a long and slow
  272. version called \.{INITEX}, which does the extra calculations needed to
  273. @.INITEX@>
  274. initialize \TeX's internal tables; and (2)~there is a shorter and faster
  275. production version, which cuts the initialization to a bare minimum.
  276. Parts of the program that are needed in (1) but not in (2) are delimited by
  277. the codewords `$|init|\ldots|tini|$'.
  278. @d init== {change this to `$\\{init}\equiv\.{@@\{}$' in the production version}
  279. @d tini== {change this to `$\\{tini}\equiv\.{@@\}}$' in the production version}
  280. @f init==begin
  281. @f tini==end
  282. @<Initialize whatever...@>=
  283. @<Set initial values of key variables@>@/
  284. @!init @<Initialize table entries (done by \.{INITEX} only)@>@;@+tini
  285. @ If the first character of a \PASCAL\ comment is a dollar sign,
  286. \ph\ treats the comment as a list of ``compiler directives'' that will
  287. affect the translation of this program into machine language.  The
  288. directives shown below specify full checking and inclusion of the \PASCAL\
  289. debugger when \TeX\ is being debugged, but they cause range checking and other
  290. redundant code to be eliminated when the production system is being generated.
  291. Arithmetic overflow will be detected in all cases.
  292. @^system dependencies@>
  293. @^Overflow in arithmetic@>
  294. @<Compiler directives@>=
  295. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  296. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  297. @ This \TeX\ implementation conforms to the rules of the {\sl Pascal User
  298. @:PASCAL}{\PASCAL@>
  299. @^system dependencies@>
  300. Manual} published by Jensen and Wirth in 1975, except where system-dependent
  301. @^Wirth, Niklaus@>
  302. @^Jensen, Kathleen@>
  303. code is necessary to make a useful system program, and except in another
  304. respect where such conformity would unnecessarily obscure the meaning
  305. and clutter up the code: We assume that |case| statements may include a
  306. default case that applies if no matching label is found. Thus, we shall use
  307. constructions like
  308. $$\vbox{\halign{\ignorespaces#\hfil\cr
  309. |case x of|\cr
  310. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  311. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  312. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  313. |endcases|\cr}}$$
  314. since most \PASCAL\ compilers have plugged this hole in the language by
  315. incorporating some sort of default mechanism. For example, the \ph\
  316. compiler allows `|others|:' as a default label, and other \PASCAL s allow
  317. syntaxes like `\&{else}' or `\&{otherwise}' or `\\{otherwise}:', etc. The
  318. definitions of |othercases| and |endcases| should be changed to agree with
  319. local conventions.  Note that no semicolon appears before |endcases| in
  320. this program, so the definition of |endcases| should include a semicolon
  321. if the compiler wants one. (Of course, if no default mechanism is
  322. available, the |case| statements of \TeX\ will have to be laboriously
  323. extended by listing all remaining cases. People who are stuck with such
  324. \PASCAL s have, in fact, done this, successfully but not happily!)
  325. @d othercases == others: {default for cases not listed explicitly}
  326. @d endcases == @+end {follows the default case in an extended |case| statement}
  327. @f othercases == else
  328. @f endcases == end
  329. @ The following parameters can be changed at compile time to extend or
  330. reduce \TeX's capacity. They may have different values in \.{INITEX} and
  331. in production versions of \TeX.
  332. @.INITEX@>
  333. @^system dependencies@>
  334. @<Constants...@>=
  335. @!mem_max=30000; {greatest index in \TeX's internal |mem| array;
  336.   must be strictly less than |max_halfword|;
  337.   must be equal to |mem_top| in \.{INITEX}, otherwise |>=mem_top|}
  338. @!mem_min=0; {smallest index in \TeX's internal |mem| array;
  339.   must be |min_halfword| or more;
  340.   must be equal to |mem_bot| in \.{INITEX}, otherwise |<=mem_bot|}
  341. @!buf_size=500; {maximum number of characters simultaneously present in
  342.   current lines of open files and in control sequences between
  343.   \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|}
  344. @!error_line=72; {width of context lines on terminal error messages}
  345. @!half_error_line=42; {width of first lines of contexts in terminal
  346.   error messages; should be between 30 and |error_line-15|}
  347. @!max_print_line=79; {width of longest text lines output; should be at least 60}
  348. @!stack_size=200; {maximum number of simultaneous input sources}
  349. @!max_in_open=6; {maximum number of input files and error insertions that
  350.   can be going on simultaneously}
  351. @!font_max=75; {maximum internal font number; must not exceed |max_quarterword|
  352.   and must be at most |font_base+256|}
  353. @!font_mem_size=20000; {number of words of |font_info| for all fonts}
  354. @!param_size=60; {maximum number of simultaneous macro parameters}
  355. @!nest_size=40; {maximum number of semantic levels simultaneously active}
  356. @!max_strings=3000; {maximum number of strings; must not exceed |max_halfword|}
  357. @!string_vacancies=8000; {the minimum number of characters that should be
  358.   available for the user's control sequences and font names,
  359.   after \TeX's own error messages are stored}
  360. @!pool_size=32000; {maximum number of characters in strings, including all
  361.   error messages and help texts, and the names of all fonts and
  362.   control sequences; must exceed |string_vacancies| by the total
  363.   length of \TeX's own strings, which is currently about 23000}
  364. @!save_size=600; {space for saving values outside of current group; must be
  365.   at most |max_halfword|}
  366. @!trie_size=8000; {space for hyphenation patterns; should be larger for
  367.   \.{INITEX} than it is in production versions of \TeX}
  368. @!trie_op_size=500; {space for ``opcodes'' in the hyphenation patterns}
  369. @!dvi_buf_size=800; {size of the output buffer; must be a multiple of 8}
  370. @!file_name_size=40; {file names shouldn't be longer than this}
  371. @!pool_name='TeXformats:TEX.POOL                     ';
  372.   {string of length |file_name_size|; tells where the string pool appears}
  373. @.TeXformats@>
  374. @ Like the preceding parameters, the following quantities can be changed
  375. at compile time to extend or reduce \TeX's capacity. But if they are changed,
  376. it is necessary to rerun the initialization program \.{INITEX}
  377. @.INITEX@>
  378. to generate new tables for the production \TeX\ program.
  379. One can't simply make helter-skelter changes to the following constants,
  380. since certain rather complex initialization
  381. numbers are computed from them. They are defined here using
  382. \.{WEB} macros, instead of being put into \PASCAL's |const| list, in order to
  383. emphasize this distinction.
  384. @d mem_bot=0 {smallest index in the |mem| array dumped by \.{INITEX};
  385.   must not be less than |mem_min|}
  386. @d mem_top==30000 {largest index in the |mem| array dumped by \.{INITEX};
  387.   must be substantially larger than |mem_bot|
  388.   and not greater than |mem_max|}
  389. @d font_base=0 {smallest internal font number; must not be less
  390.   than |min_quarterword|}
  391. @d hash_size=2100 {maximum number of control sequences; it should be at most
  392.   about |(mem_max-mem_min)/10|}
  393. @d hash_prime=1777 {a prime number equal to about 85\pct! of |hash_size|}
  394. @d hyph_size=307 {another prime; the number of \.{\\hyphenation} exceptions}
  395. @^system dependencies@>
  396. @ In case somebody has inadvertently made bad settings of the ``constants,''
  397. \TeX\ checks them using a global variable called |bad|.
  398. This is the first of many sections of \TeX\ where global variables are
  399. defined.
  400. @<Glob...@>=
  401. @!bad:integer; {is some ``constant'' wrong?}
  402. @ Later on we will say `\ignorespaces|if mem_max>=max_halfword then bad:=14|',
  403. or something similar. (We can't do that until |max_halfword| has been defined.)
  404. @<Check the ``constant'' values for consistency@>=
  405. bad:=0;
  406. if (half_error_line<30)or(half_error_line>error_line-15) then bad:=1;
  407. if max_print_line<60 then bad:=2;
  408. if dvi_buf_size mod 8<>0 then bad:=3;
  409. if mem_bot+1100>mem_top then bad:=4;
  410. if hash_prime>hash_size then bad:=5;
  411. if max_in_open>=128 then bad:=6;
  412. if mem_top<256+11 then bad:=7; {we will want |null_list>255|}
  413. @ Labels are given symbolic names by the following definitions, so that
  414. occasional |goto| statements will be meaningful. We insert the label
  415. `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
  416. which we have used the `|return|' statement defined below; the label
  417. `|restart|' is occasionally used at the very beginning of a procedure; and
  418. the label `|reswitch|' is occasionally used just prior to a |case|
  419. statement in which some cases change the conditions and we wish to branch
  420. to the newly applicable case.  Loops that are set up with the |loop|
  421. construction defined below are commonly exited by going to `|done|' or to
  422. `|found|' or to `|not_found|', and they are sometimes repeated by going to
  423. `|continue|'.  If two or more parts of a subroutine start differently but
  424. end up the same, the shared code may be gathered together at
  425. `|common_ending|'.
  426. Incidentally, this program never declares a label that isn't actually used,
  427. because some fussy \PASCAL\ compilers will complain about redundant labels.
  428. @d exit=10 {go here to leave a procedure}
  429. @d restart=20 {go here to start a procedure again}
  430. @d reswitch=21 {go here to start a case statement again}
  431. @d continue=22 {go here to resume a loop}
  432. @d done=30 {go here to exit a loop}
  433. @d done1=31 {like |done|, when there is more than one loop}
  434. @d done2=32 {for exiting the second loop in a long block}
  435. @d done3=33 {for exiting the third loop in a very long block}
  436. @d done4=34 {for exiting the fourth loop in an extremely long block}
  437. @d done5=35 {for exiting the fifth loop in an immense block}
  438. @d done6=36 {for exiting the sixth loop in a block}
  439. @d found=40 {go here when you've found it}
  440. @d found1=41 {like |found|, when there's more than one per routine}
  441. @d found2=42 {like |found|, when there's more than two per routine}
  442. @d not_found=45 {go here when you've found nothing}
  443. @d common_ending=50 {go here when you want to merge with another branch}
  444. @ Here are some macros for common programming idioms.
  445. @d incr(#) == #:=#+1 {increase a variable by unity}
  446. @d decr(#) == #:=#-1 {decrease a variable by unity}
  447. @d negate(#) == #:=-# {change the sign of a variable}
  448. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  449. @f loop == xclause
  450.   {\.{WEB}'s |xclause| acts like `\ignorespaces|while true do|\unskip'}
  451. @d do_nothing == {empty statement}
  452. @d return == goto exit {terminate a procedure call}
  453. @f return == nil
  454. @d empty=0 {symbolic name for a null constant}
  455. @* \[2] The character set.
  456. In order to make \TeX\ readily portable to a wide variety of
  457. computers, all of its input text is converted to an internal eight-bit
  458. code that includes standard ASCII, the ``American Standard Code for
  459. Information Interchange.''  This conversion is done immediately when each
  460. character is read in. Conversely, characters are converted from ASCII to
  461. the user's external representation just before they are output to a
  462. text file.
  463. Such an internal code is relevant to users of \TeX\ primarily because it
  464. governs the positions of characters in the fonts. For example, the
  465. character `\.A' has ASCII code $65=@'101$, and when \TeX\ typesets
  466. this letter it specifies character number 65 in the current font.
  467. If that font actually has `\.A' in a different position, \TeX\ doesn't
  468. know what the real position is; the program that does the actual printing from
  469. \TeX's device-independent files is responsible for converting from ASCII to
  470. a particular font encoding.
  471. @^ASCII code@>
  472. \TeX's internal code also defines the value of constants
  473. that begin with a reverse apostrophe; and it provides an index to the
  474. \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
  475. tables.
  476. @ Characters of text that have been converted to \TeX's internal form
  477. are said to be of type |ASCII_code|, which is a subrange of the integers.
  478. @<Types...@>=
  479. @!ASCII_code=0..255; {eight-bit numbers}
  480. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  481. character sets were common, so it did not make provision for lowercase
  482. letters. Nowadays, of course, we need to deal with both capital and small
  483. letters in a convenient way, especially in a program for typesetting;
  484. so the present specification of \TeX\ has been written under the assumption
  485. that the \PASCAL\ compiler and run-time system permit the use of text files
  486. with more than 64 distinguishable characters. More precisely, we assume that
  487. the character set contains at least the letters and symbols associated
  488. with ASCII codes @'40 through @'176; all of these characters are now
  489. available on most computer terminals.
  490. Since we are dealing with more characters than were present in the first
  491. \PASCAL\ compilers, we have to decide what to call the associated data
  492. type. Some \PASCAL s use the original name |char| for the
  493. characters in text files, even though there now are more than 64 such
  494. characters, while other \PASCAL s consider |char| to be a 64-element
  495. subrange of a larger data type that has some other name.
  496. In order to accommodate this difference, we shall use the name |text_char|
  497. to stand for the data type of the characters that are converted to and
  498. from |ASCII_code| when they are input and output. We shall also assume
  499. that |text_char| consists of the elements |chr(first_text_char)| through
  500. |chr(last_text_char)|, inclusive. The following definitions should be
  501. adjusted if necessary.
  502. @^system dependencies@>
  503. @d text_char == char {the data type of characters in text files}
  504. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  505. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  506. @<Local variables for init...@>=
  507. @!i:integer;
  508. @ The \TeX\ processor converts between ASCII code and
  509. the user's external character set by means of arrays |xord| and |xchr|
  510. that are analogous to \PASCAL's |ord| and |chr| functions.
  511. @<Glob...@>=
  512. @!xord: array [text_char] of ASCII_code;
  513.   {specifies conversion of input characters}
  514. @!xchr: array [ASCII_code] of text_char;
  515.   {specifies conversion of output characters}
  516. @ Since we are assuming that our \PASCAL\ system is able to read and
  517. write the visible characters of standard ASCII (although not
  518. necessarily using the ASCII codes to represent them), the following
  519. assignment statements initialize the standard part of the |xchr| array
  520. properly, without needing any system-dependent changes. On the other
  521. hand, it is possible to implement \TeX\ with less complete character
  522. sets, and in such cases it will be necessary to change something here.
  523. @^system dependencies@>
  524. @<Set init...@>=
  525. xchr[@'40]:=' ';
  526. xchr[@'41]:='!';
  527. xchr[@'42]:='"';
  528. xchr[@'43]:='#';
  529. xchr[@'44]:='$';
  530. xchr[@'45]:='%';
  531. xchr[@'46]:='&';
  532. xchr[@'47]:='''';@/
  533. xchr[@'50]:='(';
  534. xchr[@'51]:=')';
  535. xchr[@'52]:='*';
  536. xchr[@'53]:='+';
  537. xchr[@'54]:=',';
  538. xchr[@'55]:='-';
  539. xchr[@'56]:='.';
  540. xchr[@'57]:='/';@/
  541. xchr[@'60]:='0';
  542. xchr[@'61]:='1';
  543. xchr[@'62]:='2';
  544. xchr[@'63]:='3';
  545. xchr[@'64]:='4';
  546. xchr[@'65]:='5';
  547. xchr[@'66]:='6';
  548. xchr[@'67]:='7';@/
  549. xchr[@'70]:='8';
  550. xchr[@'71]:='9';
  551. xchr[@'72]:=':';
  552. xchr[@'73]:=';';
  553. xchr[@'74]:='<';
  554. xchr[@'75]:='=';
  555. xchr[@'76]:='>';
  556. xchr[@'77]:='?';@/
  557. xchr[@'100]:='@@';
  558. xchr[@'101]:='A';
  559. xchr[@'102]:='B';
  560. xchr[@'103]:='C';
  561. xchr[@'104]:='D';
  562. xchr[@'105]:='E';
  563. xchr[@'106]:='F';
  564. xchr[@'107]:='G';@/
  565. xchr[@'110]:='H';
  566. xchr[@'111]:='I';
  567. xchr[@'112]:='J';
  568. xchr[@'113]:='K';
  569. xchr[@'114]:='L';
  570. xchr[@'115]:='M';
  571. xchr[@'116]:='N';
  572. xchr[@'117]:='O';@/
  573. xchr[@'120]:='P';
  574. xchr[@'121]:='Q';
  575. xchr[@'122]:='R';
  576. xchr[@'123]:='S';
  577. xchr[@'124]:='T';
  578. xchr[@'125]:='U';
  579. xchr[@'126]:='V';
  580. xchr[@'127]:='W';@/
  581. xchr[@'130]:='X';
  582. xchr[@'131]:='Y';
  583. xchr[@'132]:='Z';
  584. xchr[@'133]:='[';
  585. xchr[@'134]:='\';
  586. xchr[@'135]:=']';
  587. xchr[@'136]:='^';
  588. xchr[@'137]:='_';@/
  589. xchr[@'140]:='`';
  590. xchr[@'141]:='a';
  591. xchr[@'142]:='b';
  592. xchr[@'143]:='c';
  593. xchr[@'144]:='d';
  594. xchr[@'145]:='e';
  595. xchr[@'146]:='f';
  596. xchr[@'147]:='g';@/
  597. xchr[@'150]:='h';
  598. xchr[@'151]:='i';
  599. xchr[@'152]:='j';
  600. xchr[@'153]:='k';
  601. xchr[@'154]:='l';
  602. xchr[@'155]:='m';
  603. xchr[@'156]:='n';
  604. xchr[@'157]:='o';@/
  605. xchr[@'160]:='p';
  606. xchr[@'161]:='q';
  607. xchr[@'162]:='r';
  608. xchr[@'163]:='s';
  609. xchr[@'164]:='t';
  610. xchr[@'165]:='u';
  611. xchr[@'166]:='v';
  612. xchr[@'167]:='w';@/
  613. xchr[@'170]:='x';
  614. xchr[@'171]:='y';
  615. xchr[@'172]:='z';
  616. xchr[@'173]:='{';
  617. xchr[@'174]:='|';
  618. xchr[@'175]:='}';
  619. xchr[@'176]:='~';@/
  620. @ Some of the ASCII codes without visible characters have been given symbolic
  621. names in this program because they are used with a special meaning.
  622. @d null_code=@'0 {ASCII code that might disappear}
  623. @d carriage_return=@'15 {ASCII code used at end of line}
  624. @d invalid_code=@'177 {ASCII code that many systems prohibit in text files}
  625. @ The ASCII code is ``standard'' only to a certain extent, since many
  626. computer installations have found it advantageous to have ready access
  627. to more than 94 printing characters. Appendix~C of {\sl The \TeX book\/}
  628. gives a complete specification of the intended correspondence between
  629. characters and \TeX's internal representation.
  630. @:TeXbook}{\sl The \TeX book@>
  631. If \TeX\ is being used
  632. on a garden-variety \PASCAL\ for which only standard ASCII
  633. codes will appear in the input and output files, it doesn't really matter
  634. what codes are specified in |xchr[0..@'37]|, but the safest policy is to
  635. blank everything out by using the code shown below.
  636. However, other settings of |xchr| will make \TeX\ more friendly on
  637. computers that have an extended character set, so that users can type things
  638. like `\.^^Z' instead of `\.{\\ne}'. People with extended character sets can
  639. assign codes arbitrarily, giving an |xchr| equivalent to whatever
  640. characters the users of \TeX\ are allowed to have in their input files.
  641. It is best to make the codes correspond to the intended interpretations as
  642. shown in Appendix~C whenever possible; but this is not necessary. For
  643. example, in countries with an alphabet of more than 26 letters, it is
  644. usually best to map the additional letters into codes less than~@'40.
  645. To get the most ``permissive'' character set, change |' '| on the
  646. right of these assignment statements to |chr(i)|.
  647. @^character set dependencies@>
  648. @^system dependencies@>
  649. @<Set init...@>=
  650. for i:=0 to @'37 do xchr[i]:=' ';
  651. for i:=@'177 to @'377 do xchr[i]:=' ';
  652. @ The following system-independent code makes the |xord| array contain a
  653. suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
  654. where |i<j<@'177|, the value of |xord[xchr[i]]| will turn out to be
  655. |j| or more; hence, standard ASCII code numbers will be used instead of
  656. codes below @'40 in case there is a coincidence.
  657. @<Set init...@>=
  658. for i:=first_text_char to last_text_char do xord[chr(i)]:=invalid_code;
  659. for i:=@'200 to @'377 do xord[xchr[i]]:=i;
  660. for i:=0 to @'176 do xord[xchr[i]]:=i;
  661. @* \[3] Input and output.
  662. The bane of portability is the fact that different operating systems treat
  663. input and output quite differently, perhaps because computer scientists
  664. have not given sufficient attention to this problem. People have felt somehow
  665. that input and output are not part of ``real'' programming. Well, it is true
  666. that some kinds of programming are more fun than others. With existing
  667. input/output conventions being so diverse and so messy, the only sources of
  668. joy in such parts of the code are the rare occasions when one can find a
  669. way to make the program a little less bad than it might have been. We have
  670. two choices, either to attack I/O now and get it over with, or to postpone
  671. I/O until near the end. Neither prospect is very attractive, so let's
  672. get it over with.
  673. The basic operations we need to do are (1)~inputting and outputting of
  674. text, to or from a file or the user's terminal; (2)~inputting and
  675. outputting of eight-bit bytes, to or from a file; (3)~instructing the
  676. operating system to initiate (``open'') or to terminate (``close'') input or
  677. output from a specified file; (4)~testing whether the end of an input
  678. file has been reached.
  679. \TeX\ needs to deal with two kinds of files.
  680. We shall use the term |alpha_file| for a file that contains textual data,
  681. and the term |byte_file| for a file that contains eight-bit binary information.
  682. These two types turn out to be the same on many computers, but
  683. sometimes there is a significant distinction, so we shall be careful to
  684. distinguish between them. Standard protocols for transferring
  685. such files from computer to computer, via high-speed networks, are
  686. now becoming available to more and more communities of users.
  687. The program actually makes use also of a third kind of file, called a
  688. |word_file|, when dumping and reloading base information for its own
  689. initialization.  We shall define a word file later; but it will be possible
  690. for us to specify simple operations on word files before they are defined.
  691. @<Types...@>=
  692. @!eight_bits=0..255; {unsigned one-byte quantity}
  693. @!alpha_file=packed file of text_char; {files that contain textual data}
  694. @!byte_file=packed file of eight_bits; {files that contain binary data}
  695. @ Most of what we need to do with respect to input and output can be handled
  696. by the I/O facilities that are standard in \PASCAL, i.e., the routines
  697. called |get|, |put|, |eof|, and so on. But
  698. standard \PASCAL\ does not allow file variables to be associated with file
  699. names that are determined at run time, so it cannot be used to implement
  700. \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
  701. is crucial for our purposes. We shall assume that |name_of_file| is a variable
  702. of an appropriate type such that the \PASCAL\ run-time system being used to
  703. implement \TeX\ can open a file whose external name is specified by
  704. |name_of_file|.
  705. @^system dependencies@>
  706. @<Glob...@>=
  707. @!name_of_file:packed array[1..file_name_size] of char;@;@/
  708.   {on some systems this may be a \&{record} variable}
  709. @!name_length:0..file_name_size;@/{this many characters are actually
  710.   relevant in |name_of_file| (the rest are blank)}
  711. @ The \ph\ compiler with which the present version of \TeX\ was prepared has
  712. extended the rules of \PASCAL\ in a very convenient way. To open file~|f|,
  713. we can write
  714. $$\vbox{\halign{#\hfil\qquad&#\hfil\cr
  715. |reset(f,@t\\{name}@>,'/O')|&for input;\cr
  716. |rewrite(f,@t\\{name}@>,'/O')|&for output.\cr}}$$
  717. The `\\{name}' parameter, which is of type `{\bf packed array
  718. $[\langle\\{any}\rangle]$ of \\{char}}', stands for the name of
  719. the external file that is being opened for input or output.
  720. Blank spaces that might appear in \\{name} are ignored.
  721. The `\.{/O}' parameter tells the operating system not to issue its own
  722. error messages if something goes wrong. If a file of the specified name
  723. cannot be found, or if such a file cannot be opened for some other reason
  724. (e.g., someone may already be trying to write the same file), we will have
  725. |@!erstat(f)<>0| after an unsuccessful |reset| or |rewrite|.  This allows
  726. \TeX\ to undertake appropriate corrective action.
  727. @:PASCAL H}{\ph@>
  728. @^system dependencies@>
  729. \TeX's file-opening procedures return |false| if no file identified by
  730. |name_of_file| could be opened.
  731. @d reset_OK(#)==erstat(#)=0
  732. @d rewrite_OK(#)==erstat(#)=0
  733. @p function a_open_in(var f:alpha_file):boolean;
  734.   {open a text file for input}
  735. begin reset(f,name_of_file,'/O'); a_open_in:=reset_OK(f);
  736. function a_open_out(var f:alpha_file):boolean;
  737.   {open a text file for output}
  738. begin rewrite(f,name_of_file,'/O'); a_open_out:=rewrite_OK(f);
  739. function b_open_in(var f:byte_file):boolean;
  740.   {open a binary file for input}
  741. begin reset(f,name_of_file,'/O'); b_open_in:=reset_OK(f);
  742. function b_open_out(var f:byte_file):boolean;
  743.   {open a binary file for output}
  744. begin rewrite(f,name_of_file,'/O'); b_open_out:=rewrite_OK(f);
  745. function w_open_in(var f:word_file):boolean;
  746.   {open a word file for input}
  747. begin reset(f,name_of_file,'/O'); w_open_in:=reset_OK(f);
  748. function w_open_out(var f:word_file):boolean;
  749.   {open a word file for output}
  750. begin rewrite(f,name_of_file,'/O'); w_open_out:=rewrite_OK(f);
  751. @ Files can be closed with the \ph\ routine `|close(f)|', which
  752. @^system dependencies@>
  753. should be used when all input or output with respect to |f| has been completed.
  754. This makes |f| available to be opened again, if desired; and if |f| was used for
  755. output, the |close| operation makes the corresponding external file appear
  756. on the user's area, ready to be read.
  757. These procedures should not generate error messages if a file is
  758. being closed before it has been successfully opened.
  759. @p procedure a_close(var f:alpha_file); {close a text file}
  760. begin close(f);
  761. procedure b_close(var f:byte_file); {close a binary file}
  762. begin close(f);
  763. procedure w_close(var f:word_file); {close a word file}
  764. begin close(f);
  765. @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
  766. procedures, so we don't have to make any other special arrangements for
  767. binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
  768. The treatment of text input is more difficult, however, because
  769. of the necessary translation to |ASCII_code| values.
  770. \TeX's conventions should be efficient, and they should
  771. blend nicely with the user's operating environment.
  772. @ Input from text files is read one line at a time, using a routine called
  773. |input_ln|. This function is defined in terms of global variables called
  774. |buffer|, |first|, and |last| that will be described in detail later; for
  775. now, it suffices for us to know that |buffer| is an array of |ASCII_code|
  776. values, and that |first| and |last| are indices into this array
  777. representing the beginning and ending of a line of text.
  778. @<Glob...@>=
  779. @!buffer:array[0..buf_size] of ASCII_code; {lines of characters being read}
  780. @!first:0..buf_size; {the first unused position in |buffer|}
  781. @!last:0..buf_size; {end of the line just input to |buffer|}
  782. @!max_buf_stack:0..buf_size; {largest index used in |buffer|}
  783. @ The |input_ln| function brings the next line of input from the specified
  784. file into available positions of the buffer array and returns the value
  785. |true|, unless the file has already been entirely read, in which case it
  786. returns |false| and sets |last:=first|.  In general, the |ASCII_code|
  787. numbers that represent the next line of the file are input into
  788. |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
  789. global variable |last| is set equal to |first| plus the length of the
  790. line. Trailing blanks are removed from the line; thus, either |last=first|
  791. (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
  792. An overflow error is given, however, if the normal actions of |input_ln|
  793. would make |last>=buf_size|; this is done so that other parts of \TeX\
  794. can safely look at the contents of |buffer[last+1]| without overstepping
  795. the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
  796. |first<buf_size| will always hold, so that there is always room for an
  797. ``empty'' line.
  798. The variable |max_buf_stack|, which is used to keep track of how large
  799. the |buf_size| parameter must be to accommodate the present job, is
  800. also kept up to date by |input_ln|.
  801. If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
  802. before looking at the first character of the line; this skips over
  803. an |eoln| that was in |f^|. The procedure does not do a |get| when it
  804. reaches the end of the line; therefore it can be used to acquire input
  805. from the user's terminal as well as from ordinary text files.
  806. Standard \PASCAL\ says that a file should have |eoln| immediately
  807. before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
  808. occurs in the middle of a line, the system function |eoln| should return
  809. a |true| result (even though |f^| will be undefined).
  810. Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
  811. character of input comes in at this place---it is wise to reduce system
  812. overhead by making use of special routines that read in an entire array
  813. of characters at once, if such routines are available. The following
  814. code uses standard \PASCAL\ to illustrate what needs to be done, but
  815. finer tuning is often possible at well-developed \PASCAL\ sites.
  816. @^inner loop@>
  817. @p function input_ln(var f:alpha_file;@!bypass_eoln:boolean):boolean;
  818.   {inputs the next line or returns |false|}
  819. var last_nonblank:0..buf_size; {|last| with trailing blanks removed}
  820. begin if bypass_eoln then if not eof(f) then get(f);
  821.   {input the first character of the line into |f^|}
  822. last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
  823. if eof(f) then input_ln:=false
  824. else  begin last_nonblank:=first;
  825.   while not eoln(f) do
  826.     begin if last>=max_buf_stack then
  827.       begin max_buf_stack:=last+1;
  828.       if max_buf_stack=buf_size then
  829.         @<Report overflow of the input buffer, and abort@>;
  830.       end;
  831.     buffer[last]:=xord[f^]; get(f); incr(last);
  832.     if buffer[last-1]<>" " then last_nonblank:=last;
  833.     end;
  834.   last:=last_nonblank; input_ln:=true;
  835.   end;
  836. @ The user's terminal acts essentially like other files of text, except
  837. that it is used both for input and for output. When the terminal is
  838. considered an input file, the file variable is called |term_in|, and when it
  839. is considered an output file the file variable is |term_out|.
  840. @^system dependencies@>
  841. @<Glob...@>=
  842. @!term_in:alpha_file; {the terminal as an input file}
  843. @!term_out:alpha_file; {the terminal as an output file}
  844. @ Here is how to open the terminal files
  845. in \ph. The `\.{/I}' switch suppresses the first |get|.
  846. @^system dependencies@>
  847. @d t_open_in==reset(term_in,'TTY:','/O/I') {open the terminal for text input}
  848. @d t_open_out==rewrite(term_out,'TTY:','/O') {open the terminal for text output}
  849. @ Sometimes it is necessary to synchronize the input/output mixture that
  850. happens on the user's terminal, and three system-dependent
  851. procedures are used for this
  852. purpose. The first of these, |update_terminal|, is called when we want
  853. to make sure that everything we have output to the terminal so far has
  854. actually left the computer's internal buffers and been sent.
  855. The second, |clear_terminal|, is called when we wish to cancel any
  856. input that the user may have typed ahead (since we are about to
  857. issue an unexpected error message). The third, |wake_up_terminal|,
  858. is supposed to revive the terminal if the user has disabled it by
  859. some instruction to the operating system.  The following macros show how
  860. these operations can be specified in \ph:
  861. @^system dependencies@>
  862. @d update_terminal == break(term_out) {empty the terminal output buffer}
  863. @d clear_terminal == break_in(term_in,true) {clear the terminal input buffer}
  864. @d wake_up_terminal == do_nothing {cancel the user's cancellation of output}
  865. @ We need a special routine to read the first line of \TeX\ input from
  866. the user's terminal. This line is different because it is read before we
  867. have opened the transcript file; there is sort of a ``chicken and
  868. egg'' problem here. If the user types `\.{\\input paper}' on the first
  869. line, or if some macro invoked by that line does such an \.{\\input},
  870. the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
  871. commands are performed during the first line of terminal input, the transcript
  872. file will acquire its default name `\.{texput.log}'. (The transcript file
  873. will not contain error messages generated by the first line before the
  874. first \.{\\input} command.)
  875. @.texput@>
  876. The first line is even more special if we are lucky enough to have an operating
  877. system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
  878. program. It's nice to let the user start running a \TeX\ job by typing
  879. a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
  880. as if the first line of input were `\.{paper}', i.e., the first line will
  881. consist of the remainder of the command line, after the part that invoked
  882. \TeX.
  883. The first line is special also because it may be read before \TeX\ has
  884. input a format file. In such cases, normal error messages cannot yet
  885. be given. The following code uses concepts that will be explained later.
  886. (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
  887. @^system dependencies@>
  888. statement `|goto final_end|' should be replaced by something that
  889. quietly terminates the program.)
  890. @<Report overflow of the input buffer, and abort@>=
  891. if format_ident=0 then
  892.   begin write_ln(term_out,'Buffer size exceeded!'); goto final_end;
  893. @.Buffer size exceeded@>
  894.   end
  895. else begin cur_input.loc_field:=first; cur_input.limit_field:=last-1;
  896.   overflow("buffer size",buf_size);
  897. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  898.   end
  899. @ Different systems have different ways to get started. But regardless of
  900. what conventions are adopted, the routine that initializes the terminal
  901. should satisfy the following specifications:
  902. \yskip\textindent{1)}It should open file |term_in| for input from the
  903.   terminal. (The file |term_out| will already be open for output to the
  904.   terminal.)
  905. \textindent{2)}If the user has given a command line, this line should be
  906.   considered the first line of terminal input. Otherwise the
  907.   user should be prompted with `\.{**}', and the first line of input
  908.   should be whatever is typed in response.
  909. \textindent{3)}The first line of input, which might or might not be a
  910.   command line, should appear in locations |first| to |last-1| of the
  911.   |buffer| array.
  912. \textindent{4)}The global variable |loc| should be set so that the
  913.   character to be read next by \TeX\ is in |buffer[loc]|. This
  914.   character should not be blank, and we should have |loc<last|.
  915. \yskip\noindent(It may be necessary to prompt the user several times
  916. before a non-blank line comes in. The prompt is `\.{**}' instead of the
  917. later `\.*' because the meaning is slightly different: `\.{\\input}' need
  918. not be typed immediately after~`\.{**}'.)
  919. @d loc==cur_input.loc_field {location of first unread character in |buffer|}
  920. @ The following program does the required initialization
  921. without retrieving a possible command line.
  922. It should be clear how to modify this routine to deal with command lines,
  923. if the system permits them.
  924. @^system dependencies@>
  925. @p function init_terminal:boolean; {gets the terminal input started}
  926. label exit;
  927. begin t_open_in;
  928. loop@+begin wake_up_terminal; write(term_out,'**'); update_terminal;
  929. @.**@>
  930.   if not input_ln(term_in,true) then {this shouldn't happen}
  931.     begin write_ln(term_out);
  932.     write(term_out,'! End of file on the terminal... why?');
  933. @.End of file on the terminal@>
  934.     init_terminal:=false; return;
  935.     end;
  936.   loc:=first;
  937.   while (loc<last)and(buffer[loc]=" ") do incr(loc);
  938.   if loc<last then
  939.     begin init_terminal:=true;
  940.     return; {return unless the line was all blank}
  941.     end;
  942.   write_ln(term_out,'Please type the name of your input file.');
  943.   end;
  944. exit:end;
  945. @* \[4] String handling.
  946. Control sequence names and diagnostic messages are variable-length strings
  947. of eight-bit characters. Since \PASCAL\ does not have a well-developed string
  948. mechanism, \TeX\ does all of its string processing by homegrown methods.
  949. Elaborate facilities for dynamic strings are not needed, so all of the
  950. necessary operations can be handled with a simple data structure.
  951. The array |str_pool| contains all of the (eight-bit) ASCII codes in all
  952. of the strings, and the array |str_start| contains indices of the starting
  953. points of each string. Strings are referred to by integer numbers, so that
  954. string number |s| comprises the characters |str_pool[j]| for
  955. |str_start[s]<=j<str_start[s+1]|. Additional integer variables
  956. |pool_ptr| and |str_ptr| indicate the number of entries used so far
  957. in |str_pool| and |str_start|, respectively; locations
  958. |str_pool[pool_ptr]| and |str_start[str_ptr]| are
  959. ready for the next string to be allocated.
  960. String numbers 0 to 255 are reserved for strings that correspond to single
  961. ASCII characters. This is in accordance with the conventions of \.{WEB},
  962. @.WEB@>
  963. which converts single-character strings into the ASCII code number of the
  964. single character involved, while it converts other strings into integers
  965. and builds a string pool file. Thus, when the string constant \.{"."} appears
  966. in the program below, \.{WEB} converts it into the integer 46, which is the
  967. ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
  968. into some integer greater than~255. String number 46 will presumably be the
  969. single character `\..'; but some ASCII codes have no standard visible
  970. representation, and \TeX\ sometimes needs to be able to print an arbitrary
  971. ASCII character, so the first 256 strings are used to specify exactly what
  972. should be printed for each of the 256 possibilities.
  973. Elements of the |str_pool| array must be ASCII codes that can actually
  974. be printed; i.e., they must have an |xchr| equivalent in the local
  975. character set. (This restriction applies only to preloaded strings,
  976. not to those generated dynamically by the user.)
  977. Some \PASCAL\ compilers won't pack integers into a single byte unless the
  978. integers lie in the range |-128..127|. To accommodate such systems
  979. we access the string pool only via macros that can easily be redefined.
  980. @d si(#) == # {convert from |ASCII_code| to |packed_ASCII_code|}
  981. @d so(#) == # {convert from |packed_ASCII_code| to |ASCII_code|}
  982. @<Types...@>=
  983. @!pool_pointer = 0..pool_size; {for variables that point into |str_pool|}
  984. @!str_number = 0..max_strings; {for variables that point into |str_start|}
  985. @!packed_ASCII_code = 0..255; {elements of |str_pool| array}
  986. @ @<Glob...@>=
  987. @!str_pool:packed array[pool_pointer] of packed_ASCII_code; {the characters}
  988. @!str_start : array[str_number] of pool_pointer; {the starting pointers}
  989. @!pool_ptr : pool_pointer; {first unused position in |str_pool|}
  990. @!str_ptr : str_number; {number of the current string being created}
  991. @!init_pool_ptr : pool_pointer; {the starting value of |pool_ptr|}
  992. @!init_str_ptr : str_number; {the starting value of |str_ptr|}
  993. @ Several of the elementary string operations are performed using \.{WEB}
  994. macros instead of \PASCAL\ procedures, because many of the
  995. operations are done quite frequently and we want to avoid the
  996. overhead of procedure calls. For example, here is
  997. a simple macro that computes the length of a string.
  998. @.WEB@>
  999. @d length(#)==(str_start[#+1]-str_start[#]) {the number of characters
  1000.   in string number \#}
  1001. @ The length of the current string is called |cur_length|:
  1002. @d cur_length == (pool_ptr - str_start[str_ptr])
  1003. @ Strings are created by appending character codes to |str_pool|.
  1004. The |append_char| macro, defined here, does not check to see if the
  1005. value of |pool_ptr| has gotten too high; this test is supposed to be
  1006. made before |append_char| is used. There is also a |flush_char|
  1007. macro, which erases the last character appended.
  1008. To test if there is room to append |l| more characters to |str_pool|,
  1009. we shall write |str_room(l)|, which aborts \TeX\ and gives an
  1010. apologetic error message if there isn't enough room.
  1011. @d append_char(#) == {put |ASCII_code| \# at the end of |str_pool|}
  1012. begin str_pool[pool_ptr]:=si(#); incr(pool_ptr);
  1013. @d flush_char == decr(pool_ptr) {forget the last character in the pool}
  1014. @d str_room(#) == {make sure that the pool hasn't overflowed}
  1015.   begin if pool_ptr+# > pool_size then
  1016.   overflow("pool size",pool_size-init_pool_ptr);
  1017. @:TeX capacity exceeded pool size}{\quad pool size@>
  1018.   end
  1019. @ Once a sequence of characters has been appended to |str_pool|, it
  1020. officially becomes a string when the function |make_string| is called.
  1021. This function returns the identification number of the new string as its
  1022. value.
  1023. @p function make_string : str_number; {current string enters the pool}
  1024. begin if str_ptr=max_strings then
  1025.   overflow("number of strings",max_strings-init_str_ptr);
  1026. @:TeX capacity exceeded number of strings}{\quad number of strings@>
  1027. incr(str_ptr); str_start[str_ptr]:=pool_ptr;
  1028. make_string:=str_ptr-1;
  1029. @ To destroy the most recently made string, we say |flush_string|.
  1030. @d flush_string==begin decr(str_ptr); pool_ptr:=str_start[str_ptr];
  1031.   end
  1032. @ The following subroutine compares string |s| with another string of the
  1033. same length that appears in |buffer| starting at position |k|;
  1034. the result is |true| if and only if the strings are equal.
  1035. Empirical tests indicate that |str_eq_buf| is used in such a way that
  1036. it tends to return |true| about 80 percent of the time.
  1037. @p function str_eq_buf(@!s:str_number;@!k:integer):boolean;
  1038.   {test equality of strings}
  1039. label not_found; {loop exit}
  1040. var j: pool_pointer; {running index}
  1041. @!result: boolean; {result of comparison}
  1042. begin j:=str_start[s];
  1043. while j<str_start[s+1] do
  1044.   begin if so(str_pool[j])<>buffer[k] then
  1045.     begin result:=false; goto not_found;
  1046.     end;
  1047.   incr(j); incr(k);
  1048.   end;
  1049. result:=true;
  1050. not_found: str_eq_buf:=result;
  1051. @ Here is a similar routine, but it compares two strings in the string pool,
  1052. and it does not assume that they have the same length.
  1053. @p function str_eq_str(@!s,@!t:str_number):boolean;
  1054.   {test equality of strings}
  1055. label not_found; {loop exit}
  1056. var j,@!k: pool_pointer; {running indices}
  1057. @!result: boolean; {result of comparison}
  1058. begin result:=false;
  1059. if length(s)<>length(t) then goto not_found;
  1060. j:=str_start[s]; k:=str_start[t];
  1061. while j<str_start[s+1] do
  1062.   begin if str_pool[j]<>str_pool[k] then goto not_found;
  1063.   incr(j); incr(k);
  1064.   end;
  1065. result:=true;
  1066. not_found: str_eq_str:=result;
  1067. @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
  1068. and |str_ptr| are computed by the \.{INITEX} program, based in part
  1069. on the information that \.{WEB} has output while processing \TeX.
  1070. @.INITEX@>
  1071. @^string pool@>
  1072. @p @!init function get_strings_started:boolean; {initializes the string pool,
  1073.   but returns |false| if something goes wrong}
  1074. label done,exit;
  1075. var k,@!l:0..255; {small indices or counters}
  1076. @!m,@!n:text_char; {characters input from |pool_file|}
  1077. @!g:str_number; {garbage}
  1078. @!a:integer; {accumulator for check sum}
  1079. @!c:boolean; {check sum has been checked}
  1080. begin pool_ptr:=0; str_ptr:=0; str_start[0]:=0;
  1081. @<Make the first 256 strings@>;
  1082. @<Read the other strings from the \.{TEX.POOL} file and return |true|,
  1083.   or give an error message and return |false|@>;
  1084. exit:end;
  1085. @ @d app_lc_hex(#)==l:=#;
  1086.   if l<10 then append_char(l+"0")@+else append_char(l-10+"a")
  1087. @<Make the first 256...@>=
  1088. for k:=0 to 255 do
  1089.   begin if (@<Character |k| cannot be printed@>) then
  1090.     begin append_char("^"); append_char("^");
  1091.     if k<@'100 then append_char(k+@'100)
  1092.     else if k<@'200 then append_char(k-@'100)
  1093.     else begin app_lc_hex(k div 16); app_lc_hex(k mod 16);
  1094.       end;
  1095.     end
  1096.   else append_char(k);
  1097.   g:=make_string;
  1098.   end
  1099. @ The first 128 strings will contain 95 standard ASCII characters, and the
  1100. other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
  1101. unless a system-dependent change is made here. Installations that have
  1102. an extended character set, where for example |xchr[@'32]=@t\.{\'^^Z\'}@>|,
  1103. would like string @'32 to be the single character @'32 instead of the
  1104. three characters @'136, @'136, @'132 (\.{\^\^Z}). On the other hand,
  1105. even people with an extended character set will want to represent string
  1106. @'15 by \.{\^\^M}, since @'15 is |carriage_return|; the idea is to
  1107. produce visible strings instead of tabs or line-feeds or carriage-returns
  1108. or bell-rings or characters that are treated anomalously in text files.
  1109. Unprintable characters of codes 128--255 are, similarly, rendered
  1110. \.{\^\^80}--\.{\^\^ff}.
  1111. The boolean expression defined here should be |true| unless \TeX\
  1112. internal code number~|k| corresponds to a non-troublesome visible
  1113. symbol in the local character set.  An appropriate formula for the
  1114. extended character set recommended in {\sl The \TeX book\/} would, for
  1115. example, be `|k in [0,@'10..@'12,@'14,@'15,@'33,@'177..@'377]|'.
  1116. If character |k| cannot be printed, and |k<@'200|, then character |k+@'100| or
  1117. |k-@'100| must be printable; moreover, ASCII codes |[@'41..@'46,
  1118. @'60..@'71, @'141..@'146, @'160..@'171]| must be printable.
  1119. Thus, at least 80 printable characters are needed.
  1120. @:TeXbook}{\sl The \TeX book@>
  1121. @^character set dependencies@>
  1122. @^system dependencies@>
  1123. @<Character |k| cannot be printed@>=
  1124.   (k<" ")or(k>"~")
  1125. @ When the \.{WEB} system program called \.{TANGLE} processes the \.{TEX.WEB}
  1126. description that you are now reading, it outputs the \PASCAL\ program
  1127. \.{TEX.PAS} and also a string pool file called \.{TEX.POOL}. The \.{INITEX}
  1128. @.WEB@>@.INITEX@>
  1129. program reads the latter file, where each string appears as a two-digit decimal
  1130. length followed by the string itself, and the information is recorded in
  1131. \TeX's string memory.
  1132. @<Glob...@>=
  1133. @!init @!pool_file:alpha_file; {the string-pool file output by \.{TANGLE}}
  1134. @ @d bad_pool(#)==begin wake_up_terminal; write_ln(term_out,#);
  1135.   a_close(pool_file); get_strings_started:=false; return;
  1136.   end
  1137. @<Read the other strings...@>=
  1138. name_of_file:=pool_name; {we needn't set |name_length|}
  1139. if a_open_in(pool_file) then
  1140.   begin c:=false;
  1141.   repeat @<Read one string, but return |false| if the
  1142.     string memory space is getting too tight for comfort@>;
  1143.   until c;
  1144.   a_close(pool_file); get_strings_started:=true;
  1145.   end
  1146. else  bad_pool('! I can''t read TEX.POOL.')
  1147. @.I can't read TEX.POOL@>
  1148. @ @<Read one string...@>=
  1149. begin if eof(pool_file) then bad_pool('! TEX.POOL has no check sum.');
  1150. @.TEX.POOL has no check sum@>
  1151. read(pool_file,m,n); {read two digits of string length}
  1152. if m='*' then @<Check the pool check sum@>
  1153. else  begin if (xord[m]<"0")or(xord[m]>"9")or@|
  1154.       (xord[n]<"0")or(xord[n]>"9") then
  1155.     bad_pool('! TEX.POOL line doesn''t begin with two digits.');
  1156. @.TEX.POOL line doesn't...@>
  1157.   l:=xord[m]*10+xord[n]-"0"*11; {compute the length}
  1158.   if pool_ptr+l+string_vacancies>pool_size then
  1159.     bad_pool('! You have to increase POOLSIZE.');
  1160. @.You have to increase POOLSIZE@>
  1161.   for k:=1 to l do
  1162.     begin if eoln(pool_file) then m:=' '@+else read(pool_file,m);
  1163.     append_char(xord[m]);
  1164.     end;
  1165.   read_ln(pool_file); g:=make_string;
  1166.   end;
  1167. @ The \.{WEB} operation \.{@@\$} denotes the value that should be at the
  1168. end of this \.{TEX.POOL} file; any other value means that the wrong pool
  1169. file has been loaded.
  1170. @^check sum@>
  1171. @<Check the pool check sum@>=
  1172. begin a:=0; k:=1;
  1173. loop@+  begin if (xord[n]<"0")or(xord[n]>"9") then
  1174.   bad_pool('! TEX.POOL check sum doesn''t have nine digits.');
  1175. @.TEX.POOL check sum...@>
  1176.   a:=10*a+xord[n]-"0";
  1177.   if k=9 then goto done;
  1178.   incr(k); read(pool_file,n);
  1179.   end;
  1180. done: if a<>@$ then bad_pool('! TEX.POOL doesn''t match; TANGLE me again.');
  1181. @.TEX.POOL doesn't match@>
  1182. c:=true;
  1183. @* \[5] On-line and off-line printing.
  1184. Messages that are sent to a user's terminal and to the transcript-log file
  1185. are produced by several `|print|' procedures. These procedures will
  1186. direct their output to a variety of places, based on the setting of
  1187. the global variable |selector|, which has the following possible
  1188. values:
  1189. \yskip
  1190. \hang |term_and_log|, the normal setting, prints on the terminal and on the
  1191.   transcript file.
  1192. \hang |log_only|, prints only on the transcript file.
  1193. \hang |term_only|, prints only on the terminal.
  1194. \hang |no_print|, doesn't print at all. This is used only in rare cases
  1195.   before the transcript file is open.
  1196. \hang |pseudo|, puts output into a cyclic buffer that is used
  1197.   by the |show_context| routine; when we get to that routine we shall discuss
  1198.   the reasoning behind this curious mode.
  1199. \hang |new_string|, appends the output to the current string in the
  1200.   string pool.
  1201. \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
  1202. \yskip
  1203. \noindent The symbolic names `|term_and_log|', etc., have been assigned
  1204. numeric codes that satisfy the convenient relations |no_print+1=term_only|,
  1205. |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.
  1206. Three additional global variables, |tally| and |term_offset| and
  1207. |file_offset|, record the number of characters that have been printed
  1208. since they were most recently cleared to zero. We use |tally| to record
  1209. the length of (possibly very long) stretches of printing; |term_offset|
  1210. and |file_offset|, on the other hand, keep track of how many characters
  1211. have appeared so far on the current line that has been output to the
  1212. terminal or to the transcript file, respectively.
  1213. @d no_print=16 {|selector| setting that makes data disappear}
  1214. @d term_only=17 {printing is destined for the terminal only}
  1215. @d log_only=18 {printing is destined for the transcript file only}
  1216. @d term_and_log=19 {normal |selector| setting}
  1217. @d pseudo=20 {special |selector| setting for |show_context|}
  1218. @d new_string=21 {printing is deflected to the string pool}
  1219. @d max_selector=21 {highest selector setting}
  1220. @<Glob...@>=
  1221. @!log_file : alpha_file; {transcript of \TeX\ session}
  1222. @!selector : 0..max_selector; {where to print a message}
  1223. @!dig : array[0..22] of 0..15; {digits in a number being output}
  1224. @!tally : integer; {the number of characters recently printed}
  1225. @!term_offset : 0..max_print_line;
  1226.   {the number of characters on the current terminal line}
  1227. @!file_offset : 0..max_print_line;
  1228.   {the number of characters on the current file line}
  1229. @!trick_buf:array[0..error_line] of ASCII_code; {circular buffer for
  1230.   pseudoprinting}
  1231. @!trick_count: integer; {threshold for pseudoprinting, explained later}
  1232. @!first_count: integer; {another variable for pseudoprinting}
  1233. @ @<Initialize the output routines@>=
  1234. selector:=term_only; tally:=0; term_offset:=0; file_offset:=0;
  1235. @ Macro abbreviations for output to the terminal and to the log file are
  1236. defined here for convenience. Some systems need special conventions
  1237. for terminal output, and it is possible to adhere to those conventions
  1238. by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
  1239. @^system dependencies@>
  1240. @d wterm(#)==write(term_out,#)
  1241. @d wterm_ln(#)==write_ln(term_out,#)
  1242. @d wterm_cr==write_ln(term_out)
  1243. @d wlog(#)==write(log_file,#)
  1244. @d wlog_ln(#)==write_ln(log_file,#)
  1245. @d wlog_cr==write_ln(log_file)
  1246. @ To end a line of text output, we call |print_ln|.
  1247. @<Basic print...@>=
  1248. procedure print_ln; {prints an end-of-line}
  1249. begin case selector of
  1250. term_and_log: begin wterm_cr; wlog_cr;
  1251.   term_offset:=0; file_offset:=0;
  1252.   end;
  1253. log_only: begin wlog_cr; file_offset:=0;
  1254.   end;
  1255. term_only: begin wterm_cr; term_offset:=0;
  1256.   end;
  1257. no_print,pseudo,new_string: do_nothing;
  1258. othercases write_ln(write_file[selector])
  1259. endcases;@/
  1260. end; {|tally| is not affected}
  1261. @ The |print_char| procedure sends one character to the desired destination,
  1262. using the |xchr| array to map it into an external character compatible with
  1263. |input_ln|. All printing comes through |print_ln| or |print_char|.
  1264. @<Basic printing...@>=
  1265. procedure print_char(@!s:ASCII_code); {prints a single character}
  1266. label exit;
  1267. begin if @<Character |s| is the current new-line character@> then
  1268.  if selector<pseudo then
  1269.   begin print_ln; return;
  1270.   end;
  1271. case selector of
  1272. term_and_log: begin wterm(xchr[s]); wlog(xchr[s]);
  1273.   incr(term_offset); incr(file_offset);
  1274.   if term_offset=max_print_line then
  1275.     begin wterm_cr; term_offset:=0;
  1276.     end;
  1277.   if file_offset=max_print_line then
  1278.     begin wlog_cr; file_offset:=0;
  1279.     end;
  1280.   end;
  1281. log_only: begin wlog(xchr[s]); incr(file_offset);
  1282.   if file_offset=max_print_line then print_ln;
  1283.   end;
  1284. term_only: begin wterm(xchr[s]); incr(term_offset);
  1285.   if term_offset=max_print_line then print_ln;
  1286.   end;
  1287. no_print: do_nothing;
  1288. pseudo: if tally<trick_count then trick_buf[tally mod error_line]:=s;
  1289. new_string: begin if pool_ptr<pool_size then append_char(s);
  1290.   end; {we drop characters if the string space is full}
  1291. othercases write(write_file[selector],xchr[s])
  1292. endcases;@/
  1293. incr(tally);
  1294. exit:end;
  1295. @ An entire string is output by calling |print|. Note that if we are outputting
  1296. the single standard ASCII character \.c, we could call |print("c")|, since
  1297. |"c"=99| is the number of a single-character string, as explained above. But
  1298. |print_char("c")| is quicker, so \TeX\ goes directly to the |print_char|
  1299. routine when it knows that this is safe. (The present implementation
  1300. assumes that it is always safe to print a visible ASCII character.)
  1301. @^system dependencies@>
  1302. @<Basic print...@>=
  1303. procedure print(@!s:integer); {prints string |s|}
  1304. label exit;
  1305. var j:pool_pointer; {current character code position}
  1306. @!nl:integer; {new-line character to restore}
  1307. begin if s>=str_ptr then s:="???" {this can't happen}
  1308. @.???@>
  1309. else if s<256 then
  1310.   if s<0 then s:="???" {can't happen}
  1311.   else begin if selector>pseudo then
  1312.       begin print_char(s); return; {internal strings are not expanded}
  1313.       end;
  1314.     if (@<Character |s| is the current new-line character@>) then
  1315.       if selector<pseudo then
  1316.         begin print_ln; return;
  1317.         end;
  1318.     nl:=new_line_char; new_line_char:=-1;
  1319.       {temporarily disable new-line character}
  1320.     j:=str_start[s];
  1321.     while j<str_start[s+1] do
  1322.       begin print_char(so(str_pool[j])); incr(j);
  1323.       end;
  1324.     new_line_char:=nl; return;
  1325.     end;
  1326. j:=str_start[s];
  1327. while j<str_start[s+1] do
  1328.   begin print_char(so(str_pool[j])); incr(j);
  1329.   end;
  1330. exit:end;
  1331. @ Control sequence names, file names, and strings constructed with
  1332. \.{\\string} might contain |ASCII_code| values that can't
  1333. be printed using |print_char|. Therefore we use |slow_print| for them:
  1334. @<Basic print...@>=
  1335. procedure slow_print(@!s:integer); {prints string |s|}
  1336. var j:pool_pointer; {current character code position}
  1337. begin if (s>=str_ptr) or (s<256) then print(s)
  1338. else begin j:=str_start[s];
  1339.   while j<str_start[s+1] do
  1340.     begin print(so(str_pool[j])); incr(j);
  1341.     end;
  1342.   end;
  1343. @ Here is the very first thing that \TeX\ prints: a headline that identifies
  1344. the version number and format package. The |term_offset| variable is temporarily
  1345. incorrect, but the discrepancy is not serious since we assume that the banner
  1346. and format identifier together will occupy at most |max_print_line|
  1347. character positions.
  1348. @<Initialize the output...@>=
  1349. wterm(banner);
  1350. if format_ident=0 then wterm_ln(' (no format preloaded)')
  1351. else  begin slow_print(format_ident); print_ln;
  1352.   end;
  1353. update_terminal;
  1354. @ The procedure |print_nl| is like |print|, but it makes sure that the
  1355. string appears at the beginning of a new line.
  1356. @<Basic print...@>=
  1357. procedure print_nl(@!s:str_number); {prints string |s| at beginning of line}
  1358. begin if ((term_offset>0)and(odd(selector)))or@|
  1359.   ((file_offset>0)and(selector>=log_only)) then print_ln;
  1360. print(s);
  1361. @ The procedure |print_esc| prints a string that is preceded by
  1362. the user's escape character (which is usually a backslash).
  1363. @<Basic print...@>=
  1364. procedure print_esc(@!s:str_number); {prints escape character, then |s|}
  1365. var c:integer; {the escape character code}
  1366. begin  @<Set variable |c| to the current escape character@>;
  1367. if c>=0 then if c<256 then print(c);
  1368. slow_print(s);
  1369. @ An array of digits in the range |0..15| is printed by |print_the_digs|.
  1370. @<Basic print...@>=
  1371. procedure print_the_digs(@!k:eight_bits);
  1372.   {prints |dig[k-1]|$\,\ldots\,$|dig[0]|}
  1373. begin while k>0 do
  1374.   begin decr(k);
  1375.   if dig[k]<10 then print_char("0"+dig[k])
  1376.   else print_char("A"-10+dig[k]);
  1377.   end;
  1378. @ The following procedure, which prints out the decimal representation of a
  1379. given integer |n|, has been written carefully so that it works properly
  1380. if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
  1381. to negative arguments, since such operations are not implemented consistently
  1382. by all \PASCAL\ compilers.
  1383. @<Basic print...@>=
  1384. procedure print_int(@!n:integer); {prints an integer in decimal form}
  1385. var k:0..23; {index to current digit; we assume that $|n|<10^{23}$}
  1386. @!m:integer; {used to negate |n| in possibly dangerous cases}
  1387. begin k:=0;
  1388. if n<0 then
  1389.   begin print_char("-");
  1390.   if n>-100000000 then negate(n)
  1391.   else  begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
  1392.     if m<10 then dig[0]:=m
  1393.     else  begin dig[0]:=0; incr(n);
  1394.       end;
  1395.     end;
  1396.   end;
  1397. repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
  1398. until n=0;
  1399. print_the_digs(k);
  1400. @ Here is a trivial procedure to print two digits; it is usually called with
  1401. a parameter in the range |0<=n<=99|.
  1402. @p procedure print_two(@!n:integer); {prints two least significant digits}
  1403. begin n:=abs(n) mod 100; print_char("0"+(n div 10));
  1404. print_char("0"+(n mod 10));
  1405. @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
  1406. @p procedure print_hex(@!n:integer);
  1407.   {prints a positive integer in hexadecimal form}
  1408. var k:0..22; {index to current digit; we assume that $0\L n<16^{22}$}
  1409. begin k:=0; print_char("""");
  1410. repeat dig[k]:=n mod 16; n:=n div 16; incr(k);
  1411. until n=0;
  1412. print_the_digs(k);
  1413. @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
  1414. is now subsumed by |print|. We retain the old name here as a possible aid to
  1415. future software arch\ae ologists.
  1416. @d print_ASCII == print
  1417. @ Roman numerals are produced by the |print_roman_int| routine.  Readers
  1418. who like puzzles might enjoy trying to figure out how this tricky code
  1419. works; therefore no explanation will be given. Notice that 1990 yields
  1420. \.{mcmxc}, not \.{mxm}.
  1421. @p procedure print_roman_int(@!n:integer);
  1422. label exit;
  1423. var j,@!k: pool_pointer; {mysterious indices into |str_pool|}
  1424. @!u,@!v: nonnegative_integer; {mysterious numbers}
  1425. begin j:=str_start["m2d5c2l5x2v5i"]; v:=1000;
  1426. loop@+  begin while n>=v do
  1427.     begin print_char(so(str_pool[j])); n:=n-v;
  1428.     end;
  1429.   if n<=0 then return; {nonpositive input produces no output}
  1430.   k:=j+2; u:=v div (so(str_pool[k-1])-"0");
  1431.   if str_pool[k-1]=si("2") then
  1432.     begin k:=k+2; u:=u div (so(str_pool[k-1])-"0");
  1433.     end;
  1434.   if n+u>=v then
  1435.     begin print_char(so(str_pool[k])); n:=n+u;
  1436.     end
  1437.   else  begin j:=j+2; v:=v div (so(str_pool[j-1])-"0");
  1438.     end;
  1439.   end;
  1440. exit:end;
  1441. @ The |print| subroutine will not print a string that is still being
  1442. created. The following procedure will.
  1443. @p procedure print_current_string; {prints a yet-unmade string}
  1444. var j:pool_pointer; {points to current character code}
  1445. begin j:=str_start[str_ptr];
  1446. while j<pool_ptr do
  1447.   begin print_char(so(str_pool[j])); incr(j);
  1448.   end;
  1449. @ Here is a procedure that asks the user to type a line of input,
  1450. assuming that the |selector| setting is either |term_only| or |term_and_log|.
  1451. The input is placed into locations |first| through |last-1| of the
  1452. |buffer| array, and echoed on the transcript file if appropriate.
  1453. This procedure is never called when |interaction<scroll_mode|.
  1454. @d prompt_input(#)==begin wake_up_terminal; print(#); term_input;
  1455.     end {prints a string and gets a line of input}
  1456. @p procedure term_input; {gets a line from the terminal}
  1457. var k:0..buf_size; {index into |buffer|}
  1458. begin update_terminal; {Now the user sees the prompt for sure}
  1459. if not input_ln(term_in,true) then fatal_error("End of file on the terminal!");
  1460. @.End of file on the terminal@>
  1461. term_offset:=0; {the user's line ended with \<\rm return>}
  1462. decr(selector); {prepare to echo the input}
  1463. if last<>first then for k:=first to last-1 do print(buffer[k]);
  1464. print_ln; incr(selector); {restore previous status}
  1465. @* \[6] Reporting errors.
  1466. When something anomalous is detected, \TeX\ typically does something like this:
  1467. $$\vbox{\halign{#\hfil\cr
  1468. |print_err("Something anomalous has been detected");|\cr
  1469. |help3("This is the first line of my offer to help.")|\cr
  1470. |("This is the second line. I'm trying to")|\cr
  1471. |("explain the best way for you to proceed.");|\cr
  1472. |error;|\cr}}$$
  1473. A two-line help message would be given using |help2|, etc.; these informal
  1474. helps should use simple vocabulary that complements the words used in the
  1475. official error message that was printed. (Outside the U.S.A., the help
  1476. messages should preferably be translated into the local vernacular. Each
  1477. line of help is at most 60 characters long, in the present implementation,
  1478. so that |max_print_line| will not be exceeded.)
  1479. The |print_err| procedure supplies a `\.!' before the official message,
  1480. and makes sure that the terminal is awake if a stop is going to occur.
  1481. The |error| procedure supplies a `\..' after the official message, then it
  1482. shows the location of the error; and if |interaction=error_stop_mode|,
  1483. it also enters into a dialog with the user, during which time the help
  1484. message may be printed.
  1485. @^system dependencies@>
  1486. @ The global variable |interaction| has four settings, representing increasing
  1487. amounts of user interaction:
  1488. @d batch_mode=0 {omits all stops and omits terminal output}
  1489. @d nonstop_mode=1 {omits all stops}
  1490. @d scroll_mode=2 {omits error stops}
  1491. @d error_stop_mode=3 {stops at every opportunity to interact}
  1492. @d print_err(#)==begin if interaction=error_stop_mode then wake_up_terminal;
  1493.   print_nl("! "); print(#);
  1494.   end
  1495. @<Glob...@>=
  1496. @!interaction:batch_mode..error_stop_mode; {current level of interaction}
  1497. @ @<Set init...@>=interaction:=error_stop_mode;
  1498. @ \TeX\ is careful not to call |error| when the print |selector| setting
  1499. might be unusual. The only possible values of |selector| at the time of
  1500. error messages are
  1501. \yskip\hang|no_print| (when |interaction=batch_mode|
  1502.   and |log_file| not yet open);
  1503. \hang|term_only| (when |interaction>batch_mode| and |log_file| not yet open);
  1504. \hang|log_only| (when |interaction=batch_mode| and |log_file| is open);
  1505. \hang|term_and_log| (when |interaction>batch_mode| and |log_file| is open).
  1506. @<Initialize the print |selector| based on |interaction|@>=
  1507. if interaction=batch_mode then selector:=no_print@+else selector:=term_only
  1508. @ A global variable |deletions_allowed| is set |false| if the |get_next|
  1509. routine is active when |error| is called; this ensures that |get_next|
  1510. and related routines like |get_token| will never be called recursively.
  1511. A similar interlock is provided by |set_box_allowed|.
  1512. @^recursion@>
  1513. The global variable |history| records the worst level of error that
  1514. has been detected. It has four possible values: |spotless|, |warning_issued|,
  1515. |error_message_issued|, and |fatal_error_stop|.
  1516. Another global variable, |error_count|, is increased by one when an
  1517. |error| occurs without an interactive dialog, and it is reset to zero at
  1518. the end of every paragraph.  If |error_count| reaches 100, \TeX\ decides
  1519. that there is no point in continuing further.
  1520. @d spotless=0 {|history| value when nothing has been amiss yet}
  1521. @d warning_issued=1 {|history| value when |begin_diagnostic| has been called}
  1522. @d error_message_issued=2 {|history| value when |error| has been called}
  1523. @d fatal_error_stop=3 {|history| value when termination was premature}
  1524. @<Glob...@>=
  1525. @!deletions_allowed:boolean; {is it safe for |error| to call |get_token|?}
  1526. @!set_box_allowed:boolean; {is it safe to do a \.{\\setbox} assignment?}
  1527. @!history:spotless..fatal_error_stop; {has the source input been clean so far?}
  1528. @!error_count:-1..100; {the number of scrolled errors since the
  1529.   last paragraph ended}
  1530. @ The value of |history| is initially |fatal_error_stop|, but it will
  1531. be changed to |spotless| if \TeX\ survives the initialization process.
  1532. @<Set init...@>=
  1533. deletions_allowed:=true; set_box_allowed:=true;
  1534. error_count:=0; {|history| is initialized elsewhere}
  1535. @ Since errors can be detected almost anywhere in \TeX, we want to declare the
  1536. error procedures near the beginning of the program. But the error procedures
  1537. in turn use some other procedures, which need to be declared |forward|
  1538. before we get to |error| itself.
  1539. It is possible for |error| to be called recursively if some error arises
  1540. when |get_token| is being used to delete a token, and/or if some fatal error
  1541. occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
  1542. @^recursion@>
  1543. is never more than two levels deep.
  1544. @<Error handling...@>=
  1545. procedure@?normalize_selector; forward;@t\2@>@/
  1546. procedure@?get_token; forward;@t\2@>@/
  1547. procedure@?term_input; forward;@t\2@>@/
  1548. procedure@?show_context; forward;@t\2@>@/
  1549. procedure@?begin_file_reading; forward;@t\2@>@/
  1550. procedure@?open_log_file; forward;@t\2@>@/
  1551. procedure@?close_files_and_terminate; forward;@t\2@>@/
  1552. procedure@?clear_for_error_prompt; forward;@t\2@>@/
  1553. procedure@?give_err_help; forward;@t\2@>@/
  1554. @t\4\hskip-\fontdimen2\font@>@;@+@!debug@+procedure@?debug_help;
  1555.   forward;@;@+gubed
  1556. @ Individual lines of help are recorded in the array |help_line|, which
  1557. contains entries in positions |0..(help_ptr-1)|. They should be printed
  1558. in reverse order, i.e., with |help_line[0]| appearing last.
  1559. @d hlp1(#)==help_line[0]:=#;@+end
  1560. @d hlp2(#)==help_line[1]:=#; hlp1
  1561. @d hlp3(#)==help_line[2]:=#; hlp2
  1562. @d hlp4(#)==help_line[3]:=#; hlp3
  1563. @d hlp5(#)==help_line[4]:=#; hlp4
  1564. @d hlp6(#)==help_line[5]:=#; hlp5
  1565. @d help0==help_ptr:=0 {sometimes there might be no help}
  1566. @d help1==@+begin help_ptr:=1; hlp1 {use this with one help line}
  1567. @d help2==@+begin help_ptr:=2; hlp2 {use this with two help lines}
  1568. @d help3==@+begin help_ptr:=3; hlp3 {use this with three help lines}
  1569. @d help4==@+begin help_ptr:=4; hlp4 {use this with four help lines}
  1570. @d help5==@+begin help_ptr:=5; hlp5 {use this with five help lines}
  1571. @d help6==@+begin help_ptr:=6; hlp6 {use this with six help lines}
  1572. @<Glob...@>=
  1573. @!help_line:array[0..5] of str_number; {helps for the next |error|}
  1574. @!help_ptr:0..6; {the number of help lines present}
  1575. @!use_err_help:boolean; {should the |err_help| list be shown?}
  1576. @ @<Set init...@>=
  1577. help_ptr:=0; use_err_help:=false;
  1578. @ The |jump_out| procedure just cuts across all active procedure levels and
  1579. goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
  1580. whole program. It is used when there is no recovery from a particular error.
  1581. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  1582. @^system dependencies@>
  1583. In such cases the body of |jump_out| should simply be
  1584. `|close_files_and_terminate|;\thinspace' followed by a call on some system
  1585. procedure that quietly terminates the program.
  1586. @<Error hand...@>=
  1587. procedure jump_out;
  1588. begin goto end_of_TEX;
  1589. @ Here now is the general |error| routine.
  1590. @<Error hand...@>=
  1591. procedure error; {completes the job of error reporting}
  1592. label continue,exit;
  1593. var c:ASCII_code; {what the user types}
  1594. @!s1,@!s2,@!s3,@!s4:integer;
  1595.   {used to save global variables when deleting tokens}
  1596. begin if history<error_message_issued then history:=error_message_issued;
  1597. print_char("."); show_context;
  1598. if interaction=error_stop_mode then @<Get user's advice and |return|@>;
  1599. incr(error_count);
  1600. if error_count=100 then
  1601.   begin print_nl("(That makes 100 errors; please try again.)");
  1602. @.That makes 100 errors...@>
  1603.   history:=fatal_error_stop; jump_out;
  1604.   end;
  1605. @<Put help message on the transcript file@>;
  1606. exit:end;
  1607. @ @<Get user's advice...@>=
  1608. loop@+begin continue: clear_for_error_prompt; prompt_input("? ");
  1609. @.?\relax@>
  1610.   if last=first then return;
  1611.   c:=buffer[first];
  1612.   if c>="a" then c:=c+"A"-"a"; {convert to uppercase}
  1613.   @<Interpret code |c| and |return| if done@>;
  1614.   end
  1615. @ It is desirable to provide an `\.E' option here that gives the user
  1616. an easy way to return from \TeX\ to the system editor, with the offending
  1617. line ready to be edited. But such an extension requires some system
  1618. wizardry, so the present implementation simply types out the name of the
  1619. file that should be
  1620. edited and the relevant line number.
  1621. @^system dependencies@>
  1622. There is a secret `\.D' option available when the debugging routines haven't
  1623. been commented~out.
  1624. @^debugging@>
  1625. @<Interpret code |c| and |return| if done@>=
  1626. case c of
  1627. "0","1","2","3","4","5","6","7","8","9": if deletions_allowed then
  1628.   @<Delete \(c)|c-"0"| tokens and |goto continue|@>;
  1629. @t\4\4@>@;@+@!debug "D": begin debug_help; goto continue;@+end;@+gubed@/
  1630. "E": if base_ptr>0 then
  1631.   begin print_nl("You want to edit file ");
  1632. @.You want to edit file x@>
  1633.   slow_print(input_stack[base_ptr].name_field);
  1634.   print(" at line "); print_int(line);
  1635.   interaction:=scroll_mode; jump_out;
  1636.   end;
  1637. "H": @<Print the help information and |goto continue|@>;
  1638. "I":@<Introduce new material from the terminal and |return|@>;
  1639. "Q","R","S":@<Change the interaction level and |return|@>;
  1640. "X":begin interaction:=scroll_mode; jump_out;
  1641.   end;
  1642. othercases do_nothing
  1643. endcases;@/
  1644. @<Print the menu of available options@>
  1645. @ @<Print the menu...@>=
  1646. begin print("Type <return> to proceed, S to scroll future error messages,");@/
  1647. @.Type <return> to proceed...@>
  1648. print_nl("R to run without stopping, Q to run quietly,");@/
  1649. print_nl("I to insert something, ");
  1650. if base_ptr>0 then print("E to edit your file,");
  1651. if deletions_allowed then
  1652.   print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
  1653. print_nl("H for help, X to quit.");
  1654. @ Here the author of \TeX\ apologizes for making use of the numerical
  1655. relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
  1656. |batch_mode|, |nonstop_mode|, |scroll_mode|.
  1657. @^Knuth, Donald Ervin@>
  1658. @<Change the interaction...@>=
  1659. begin error_count:=0; interaction:=batch_mode+c-"Q";
  1660. print("OK, entering ");
  1661. case c of
  1662. "Q":begin print_esc("batchmode"); decr(selector);
  1663.   end;
  1664. "R":print_esc("nonstopmode");
  1665. "S":print_esc("scrollmode");
  1666. end; {there are no other cases}
  1667. print("..."); print_ln; update_terminal; return;
  1668. @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
  1669. contain the material inserted by the user; otherwise another prompt will
  1670. be given. In order to understand this part of the program fully, you need
  1671. to be familiar with \TeX's input stacks.
  1672. @<Introduce new material...@>=
  1673. begin begin_file_reading; {enter a new syntactic level for terminal input}
  1674. {now |state=mid_line|, so an initial blank space will count as a blank}
  1675. if last>first+1 then
  1676.   begin loc:=first+1; buffer[first]:=" ";
  1677.   end
  1678. else  begin prompt_input("insert>"); loc:=first;
  1679. @.insert>@>
  1680.   end;
  1681. first:=last;
  1682. cur_input.limit_field:=last-1; {no |end_line_char| ends this line}
  1683. return;
  1684. @ We allow deletion of up to 99 tokens at a time.
  1685. @<Delete \(c)|c-"0"| tokens...@>=
  1686. begin s1:=cur_tok; s2:=cur_cmd; s3:=cur_chr; s4:=align_state;
  1687. align_state:=1000000; OK_to_interrupt:=false;
  1688. if (last>first+1) and (buffer[first+1]>="0")and(buffer[first+1]<="9") then
  1689.   c:=c*10+buffer[first+1]-"0"*11
  1690. else c:=c-"0";
  1691. while c>0 do
  1692.   begin get_token; {one-level recursive call of |error| is possible}
  1693.   decr(c);
  1694.   end;
  1695. cur_tok:=s1; cur_cmd:=s2; cur_chr:=s3; align_state:=s4; OK_to_interrupt:=true;
  1696. help2("I have just deleted some text, as you asked.")@/
  1697. ("You can now delete more, or insert, or whatever.");
  1698. show_context; goto continue;
  1699. @ @<Print the help info...@>=
  1700. begin if use_err_help then
  1701.   begin give_err_help; use_err_help:=false;
  1702.   end
  1703. else  begin if help_ptr=0 then
  1704.     help2("Sorry, I don't know how to help in this situation.")@/
  1705.     @t\kern1em@>("Maybe you should try asking a human?");
  1706.   repeat decr(help_ptr); print(help_line[help_ptr]); print_ln;
  1707.   until help_ptr=0;
  1708.   end;
  1709. help4("Sorry, I already gave what help I could...")@/
  1710.   ("Maybe you should try asking a human?")@/
  1711.   ("An error might have occurred before I noticed any problems.")@/
  1712.   ("``If all else fails, read the instructions.''");@/
  1713. goto continue;
  1714. @ @<Put help message on the transcript file@>=
  1715. if interaction>batch_mode then decr(selector); {avoid terminal output}
  1716. if use_err_help then
  1717.   begin print_ln; give_err_help;
  1718.   end
  1719. else while help_ptr>0 do
  1720.   begin decr(help_ptr); print_nl(help_line[help_ptr]);
  1721.   end;
  1722. print_ln;
  1723. if interaction>batch_mode then incr(selector); {re-enable terminal output}
  1724. print_ln
  1725. @ A dozen or so error messages end with a parenthesized integer, so we
  1726. save a teeny bit of program space by declaring the following procedure:
  1727. @p procedure int_error(@!n:integer);
  1728. begin print(" ("); print_int(n); print_char(")"); error;
  1729. @ In anomalous cases, the print selector might be in an unknown state;
  1730. the following subroutine is called to fix things just enough to keep
  1731. running a bit longer.
  1732. @p procedure normalize_selector;
  1733. begin if log_opened then selector:=term_and_log
  1734. else selector:=term_only;
  1735. if job_name=0 then open_log_file;
  1736. if interaction=batch_mode then decr(selector);
  1737. @ The following procedure prints \TeX's last words before dying.
  1738. @d succumb==begin if interaction=error_stop_mode then
  1739.     interaction:=scroll_mode; {no more interaction}
  1740.   if log_opened then error;
  1741.   @!debug if interaction>batch_mode then debug_help;@+gubed@;@/
  1742.   history:=fatal_error_stop; jump_out; {irrecoverable error}
  1743.   end
  1744. @<Error hand...@>=
  1745. procedure fatal_error(@!s:str_number); {prints |s|, and that's it}
  1746. begin normalize_selector;@/
  1747. print_err("Emergency stop"); help1(s); succumb;
  1748. @.Emergency stop@>
  1749. @ Here is the most dreaded error message.
  1750. @<Error hand...@>=
  1751. procedure overflow(@!s:str_number;@!n:integer); {stop due to finiteness}
  1752. begin normalize_selector;
  1753. print_err("TeX capacity exceeded, sorry [");
  1754. @.TeX capacity exceeded ...@>
  1755. print(s); print_char("="); print_int(n); print_char("]");
  1756. help2("If you really absolutely need more capacity,")@/
  1757.   ("you can ask a wizard to enlarge me.");
  1758. succumb;
  1759. @ The program might sometime run completely amok, at which point there is
  1760. no choice but to stop. If no previous error has been detected, that's bad
  1761. news; a message is printed that is really intended for the \TeX\
  1762. maintenance person instead of the user (unless the user has been
  1763. particularly diabolical).  The index entries for `this can't happen' may
  1764. help to pinpoint the problem.
  1765. @^dry rot@>
  1766. @<Error hand...@>=
  1767. procedure confusion(@!s:str_number);
  1768.   {consistency check violated; |s| tells where}
  1769. begin normalize_selector;
  1770. if history<error_message_issued then
  1771.   begin print_err("This can't happen ("); print(s); print_char(")");
  1772. @.This can't happen@>
  1773.   help1("I'm broken. Please show this to someone who can fix can fix");
  1774.   end
  1775. else  begin print_err("I can't go on meeting you like this");
  1776. @.I can't go on...@>
  1777.   help2("One of your faux pas seems to have wounded me deeply...")@/
  1778.     ("in fact, I'm barely conscious. Please fix it and try again.");
  1779.   end;
  1780. succumb;
  1781. @ Users occasionally want to interrupt \TeX\ while it's running.
  1782. If the \PASCAL\ runtime system allows this, one can implement
  1783. a routine that sets the global variable |interrupt| to some nonzero value
  1784. when such an interrupt is signalled. Otherwise there is probably at least
  1785. a way to make |interrupt| nonzero using the \PASCAL\ debugger.
  1786. @^system dependencies@>
  1787. @^debugging@>
  1788. @d check_interrupt==begin if interrupt<>0 then pause_for_instructions;
  1789.   end
  1790. @<Global...@>=
  1791. @!interrupt:integer; {should \TeX\ pause for instructions?}
  1792. @!OK_to_interrupt:boolean; {should interrupts be observed?}
  1793. @ @<Set init...@>=
  1794. interrupt:=0; OK_to_interrupt:=true;
  1795. @ When an interrupt has been detected, the program goes into its
  1796. highest interaction level and lets the user have nearly the full flexibility of
  1797. the |error| routine.  \TeX\ checks for interrupts only at times when it is
  1798. safe to do this.
  1799. @p procedure pause_for_instructions;
  1800. begin if OK_to_interrupt then
  1801.   begin interaction:=error_stop_mode;
  1802.   if (selector=log_only)or(selector=no_print) then
  1803.     incr(selector);
  1804.   print_err("Interruption");
  1805. @.Interruption@>
  1806.   help3("You rang?")@/
  1807.   ("Try to insert some instructions for me (e.g.,`I\showlists'),")@/
  1808.   ("unless you just want to quit by typing `X'.");
  1809.   deletions_allowed:=false; error; deletions_allowed:=true;
  1810.   interrupt:=0;
  1811.   end;
  1812. @* \[7] Arithmetic with scaled dimensions.
  1813. The principal computations performed by \TeX\ are done entirely in terms of
  1814. integers less than $2^{31}$ in magnitude; and divisions are done only when both
  1815. dividend and divisor are nonnegative. Thus, the arithmetic specified in this
  1816. program can be carried out in exactly the same way on a wide variety of
  1817. computers, including some small ones. Why? Because the arithmetic
  1818. calculations need to be spelled out precisely in order to guarantee that
  1819. \TeX\ will produce identical output on different machines. If some
  1820. quantities were rounded differently in different implementations, we would
  1821. find that line breaks and even page breaks might occur in different places.
  1822. Hence the arithmetic of \TeX\ has been designed with care, and systems that
  1823. claim to be implementations of \TeX82 should follow precisely the
  1824. @:TeX82}{\TeX82@>
  1825. calculations as they appear in the present program.
  1826. (Actually there are three places where \TeX\ uses |div| with a possibly negative
  1827. numerator. These are harmless; see |div| in the index. Also if the user
  1828. sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
  1829. information will involve negative-numerator division. The same remarks
  1830. apply for |mod| as well as for |div|.)
  1831. @ Here is a routine that calculates half of an integer, using an
  1832. unambiguous convention with respect to signed odd numbers.
  1833. @p function half(@!x:integer):integer;
  1834. begin if odd(x) then half:=(x+1) div 2
  1835. else half:=x @!div 2;
  1836. @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
  1837. of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
  1838. positions from the right end of a binary computer word.
  1839. @d unity == @'200000 {$2^{16}$, represents 1.00000}
  1840. @d two == @'400000 {$2^{17}$, represents 2.00000}
  1841. @<Types...@>=
  1842. @!scaled = integer; {this type is used for scaled integers}
  1843. @!nonnegative_integer=0..@'17777777777; {$0\L x<2^{31}$}
  1844. @!small_number=0..63; {this type is self-explanatory}
  1845. @ The following function is used to create a scaled integer from a given decimal
  1846. fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
  1847. given in |dig[i]|, and the calculation produces a correctly rounded result.
  1848. @p function round_decimals(@!k:small_number) : scaled;
  1849.   {converts a decimal fraction}
  1850. var a:integer; {the accumulator}
  1851. begin a:=0;
  1852. while k>0 do
  1853.   begin decr(k); a:=(a+dig[k]*two) div 10;
  1854.   end;
  1855. round_decimals:=(a+1) div 2;
  1856. @ Conversely, here is a procedure analogous to |print_int|. If the output
  1857. of this procedure is subsequently read by \TeX\ and converted by the
  1858. |round_decimals| routine above, it turns out that the original value will
  1859. be reproduced exactly; the ``simplest'' such decimal number is output,
  1860. but there is always at least one digit following the decimal point.
  1861. The invariant relation in the \&{repeat} loop is that a sequence of
  1862. decimal digits yet to be printed will yield the original number if and only if
  1863. they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
  1864. We can stop if and only if $f=0$ satisfies this condition; the loop will
  1865. terminate before $s$ can possibly become zero.
  1866. @p procedure print_scaled(@!s:scaled); {prints scaled real, rounded to five
  1867.   digits}
  1868. var delta:scaled; {amount of allowable inaccuracy}
  1869. begin if s<0 then
  1870.   begin print_char("-"); negate(s); {print the sign, if negative}
  1871.   end;
  1872. print_int(s div unity); {print the integer part}
  1873. print_char(".");
  1874. s:=10*(s mod unity)+5; delta:=10;
  1875. repeat if delta>unity then s:=s+@'100000-50000; {round the last digit}
  1876. print_char("0"+(s div unity)); s:=10*(s mod unity); delta:=delta*10;
  1877. until s<=delta;
  1878. @ Physical sizes that a \TeX\ user specifies for portions of documents are
  1879. represented internally as scaled points. Thus, if we define an `sp' (scaled
  1880. @^sp@>
  1881. point) as a unit equal to $2^{-16}$ printer's points, every dimension
  1882. inside of \TeX\ is an integer number of sp. There are exactly
  1883. 4,736,286.72 sp per inch.  Users are not allowed to specify dimensions
  1884. larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
  1885. meters); two such quantities can be added without overflow on a 32-bit
  1886. computer.
  1887. The present implementation of \TeX\ does not check for overflow when
  1888. @^Overflow in arithmetic@>
  1889. dimensions are added or subtracted. This could be done by inserting a
  1890. few dozen tests of the form `\ignorespaces|if x>=@'10000000000 then
  1891. @t\\{report\_overflow}@>|', but the chance of overflow is so remote that
  1892. such tests do not seem worthwhile.
  1893. \TeX\ needs to do only a few arithmetic operations on scaled quantities,
  1894. other than addition and subtraction, and the following subroutines do most of
  1895. the work. A single computation might use several subroutine calls, and it is
  1896. desirable to avoid producing multiple error messages in case of arithmetic
  1897. overflow; so the routines set the global variable |arith_error| to |true|
  1898. instead of reporting errors directly to the user. Another global variable,
  1899. |remainder|, holds the remainder after a division.
  1900. @<Glob...@>=
  1901. @!arith_error:boolean; {has arithmetic overflow occurred recently?}
  1902. @!remainder:scaled; {amount subtracted to get an exact division}
  1903. @ The first arithmetical subroutine we need computes $nx+y$, where |x|
  1904. and~|y| are |scaled| and |n| is an integer. We will also use it to
  1905. multiply integers.
  1906. @d nx_plus_y(#)==mult_and_add(#,@'7777777777)
  1907. @d mult_integers(#)==mult_and_add(#,0,@'17777777777)
  1908. @p function mult_and_add(@!n:integer;@!x,@!y,@!max_answer:scaled):scaled;
  1909. begin if n<0 then
  1910.   begin negate(x); negate(n);
  1911.   end;
  1912. if n=0 then mult_and_add:=y
  1913. else if ((x<=(max_answer-y) div n)and(-x<=(max_answer+y) div n)) then
  1914.   mult_and_add:=n*x+y
  1915. else  begin arith_error:=true; mult_and_add:=0;
  1916.   end;
  1917. @ We also need to divide scaled dimensions by integers.
  1918. @p function x_over_n(@!x:scaled;@!n:integer):scaled;
  1919. var negative:boolean; {should |remainder| be negated?}
  1920. begin negative:=false;
  1921. if n=0 then
  1922.   begin arith_error:=true; x_over_n:=0; remainder:=x;
  1923.   end
  1924. else  begin if n<0 then
  1925.     begin negate(x); negate(n); negative:=true;
  1926.     end;
  1927.   if x>=0 then
  1928.     begin x_over_n:=x div n; remainder:=x mod n;
  1929.     end
  1930.   else  begin x_over_n:=-((-x) div n); remainder:=-((-x) mod n);
  1931.     end;
  1932.   end;
  1933. if negative then negate(remainder);
  1934. @ Then comes the multiplication of a scaled number by a fraction |n/d|,
  1935. where |n| and |d| are nonnegative integers |<=@t$2^{16}$@>| and |d| is
  1936. positive. It would be too dangerous to multiply by~|n| and then divide
  1937. by~|d|, in separate operations, since overflow might well occur; and it
  1938. would be too inaccurate to divide by |d| and then multiply by |n|. Hence
  1939. this subroutine simulates 1.5-precision arithmetic.
  1940. @p function xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
  1941. var positive:boolean; {was |x>=0|?}
  1942. @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
  1943. begin if x>=0 then positive:=true
  1944. else  begin negate(x); positive:=false;
  1945.   end;
  1946. t:=(x mod @'100000)*n;
  1947. u:=(x div @'100000)*n+(t div @'100000);
  1948. v:=(u mod d)*@'100000 + (t mod @'100000);
  1949. if u div d>=@'100000 then arith_error:=true
  1950. else u:=@'100000*(u div d) + (v div d);
  1951. if positive then
  1952.   begin xn_over_d:=u; remainder:=v mod d;
  1953.   end
  1954. else  begin xn_over_d:=-u; remainder:=-(v mod d);
  1955.   end;
  1956. @ The next subroutine is used to compute the ``badness'' of glue, when a
  1957. total~|t| is supposed to be made from amounts that sum to~|s|.  According
  1958. to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
  1959. however, badness is simply a heuristic, so we need not squeeze out the
  1960. last drop of accuracy when computing it. All we really want is an
  1961. approximation that has similar properties.
  1962. @:TeXbook}{\sl The \TeX book@>
  1963. The actual method used to compute the badness is easier to read from the
  1964. program than to describe in words. It produces an integer value that is a
  1965. reasonably close approximation to $100(t/s)^3$, and all implementations
  1966. of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
  1967. treated as infinitely bad, and represented by 10000.
  1968. It is not difficult to prove that $$\hbox{|badness(t+1,s)>=badness(t,s)
  1969. >=badness(t,s+1)|}.$$ The badness function defined here is capable of
  1970. computing at most 1095 distinct values, but that is plenty.
  1971. @d inf_bad = 10000 {infinitely bad value}
  1972. @p function badness(@!t,@!s:scaled):halfword; {compute badness, given |t>=0|}
  1973. var r:integer; {approximation to $\alpha t/s$, where $\alpha^3\approx
  1974.   100\cdot2^{18}$}
  1975. begin if t=0 then badness:=0
  1976. else if s<=0 then badness:=inf_bad
  1977. else  begin if t<=7230584 then  r:=(t*297) div s {$297^3=99.94\times2^{18}$}
  1978.   else if s>=1663497 then r:=t div (s div 297)
  1979.   else r:=t;
  1980.   if r>1290 then badness:=inf_bad {$1290^3<2^{31}<1291^3$}
  1981.   else badness:=(r*r*r+@'400000) div @'1000000;
  1982.   end; {that was $r^3/2^{18}$, rounded to the nearest integer}
  1983. @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
  1984. proportionality ratio by which the glue inside the box should stretch
  1985. or shrink. This calculation does not affect \TeX's decision making,
  1986. so the precise details of rounding, etc., in the glue calculation are not
  1987. of critical importance for the consistency of results on different computers.
  1988. We shall use the type |glue_ratio| for such proportionality ratios.
  1989. A glue ratio should take the same amount of memory as an
  1990. |integer| (usually 32 bits) if it is to blend smoothly with \TeX's
  1991. other data structures. Thus |glue_ratio| should be equivalent to
  1992. |short_real| in some implementations of \PASCAL. Alternatively,
  1993. it is possible to deal with glue ratios using nothing but fixed-point
  1994. arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
  1995. routines cited there must be modified to allow negative glue ratios.)
  1996. @^system dependencies@>
  1997. @d set_glue_ratio_zero(#) == #:=0.0 {store the representation of zero ratio}
  1998. @d set_glue_ratio_one(#) == #:=1.0 {store the representation of unit ratio}
  1999. @d float(#) == # {convert from |glue_ratio| to type |real|}
  2000. @d unfloat(#) == # {convert from |real| to type |glue_ratio|}
  2001. @d float_constant(#) == #.0 {convert |integer| constant to |real|}
  2002. @<Types...@>=
  2003. @!glue_ratio=real; {one-word representation of a glue expansion factor}
  2004. @* \[8] Packed data.
  2005. In order to make efficient use of storage space, \TeX\ bases its major data
  2006. structures on a |memory_word|, which contains either a (signed) integer,
  2007. possibly scaled, or a (signed) |glue_ratio|, or a small number of
  2008. fields that are one half or one quarter of the size used for storing
  2009. integers.
  2010. If |x| is a variable of type |memory_word|, it contains up to four
  2011. fields that can be referred to as follows:
  2012. $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
  2013. |x|&.|int|&(an |integer|)\cr
  2014. |x|&.|sc|\qquad&(a |scaled| integer)\cr
  2015. |x|&.|gr|&(a |glue_ratio|)\cr
  2016. |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
  2017. |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
  2018.   field)\cr
  2019. |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
  2020.   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
  2021. This is somewhat cumbersome to write, and not very readable either, but
  2022. macros will be used to make the notation shorter and more transparent.
  2023. The \PASCAL\ code below gives a formal definition of |memory_word| and
  2024. its subsidiary types, using packed variant records. \TeX\ makes no
  2025. assumptions about the relative positions of the fields within a word.
  2026. Since we are assuming 32-bit integers, a halfword must contain at least
  2027. 16 bits, and a quarterword must contain at least 8 bits.
  2028. @^system dependencies@>
  2029. But it doesn't hurt to have more bits; for example, with enough 36-bit
  2030. words you might be able to have |mem_max| as large as 262142, which is
  2031. eight times as much memory as anybody had during the first four years of
  2032. \TeX's existence.
  2033. N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
  2034. by a \PASCAL\ that packs all of the |memory_word| variants into
  2035. the space of a single integer. This means, for example, that |glue_ratio|
  2036. words should be |short_real| instead of |real| on some computers. Some
  2037. \PASCAL\ compilers will pack an integer whose subrange is `|0..255|' into
  2038. an eight-bit field, but others insist on allocating space for an additional
  2039. sign bit; on such systems you can get 256 values into a quarterword only
  2040. if the subrange is `|-128..127|'.
  2041. The present implementation tries to accommodate as many variations as possible,
  2042. so it makes few assumptions. If integers having the subrange
  2043. `|min_quarterword..max_quarterword|' can be packed into a quarterword,
  2044. and if integers having the subrange `|min_halfword..max_halfword|'
  2045. can be packed into a halfword, everything should work satisfactorily.
  2046. It is usually most efficient to have |min_quarterword=min_halfword=0|,
  2047. so one should try to achieve this unless it causes a severe problem.
  2048. The values defined here are recommended for most 32-bit computers.
  2049. @d min_quarterword=0 {smallest allowable value in a |quarterword|}
  2050. @d max_quarterword=255 {largest allowable value in a |quarterword|}
  2051. @d min_halfword==0 {smallest allowable value in a |halfword|}
  2052. @d max_halfword==65535 {largest allowable value in a |halfword|}
  2053. @ Here are the inequalities that the quarterword and halfword values
  2054. must satisfy (or rather, the inequalities that they mustn't satisfy):
  2055. @<Check the ``constant''...@>=
  2056. init if (mem_min<>mem_bot)or(mem_max<>mem_top) then bad:=10;@+tini@;@/
  2057. if (mem_min>mem_bot)or(mem_max<mem_top) then bad:=10;
  2058. if (min_quarterword>0)or(max_quarterword<127) then bad:=11;
  2059. if (min_halfword>0)or(max_halfword<32767) then bad:=12;
  2060. if (min_quarterword<min_halfword)or@|
  2061.   (max_quarterword>max_halfword) then bad:=13;
  2062. if (mem_min<min_halfword)or(mem_max>=max_halfword)or@|
  2063.   (mem_bot-mem_min>max_halfword+1) then bad:=14;
  2064. if (font_base<min_quarterword)or(font_max>max_quarterword) then bad:=15;
  2065. if font_max>font_base+256 then bad:=16;
  2066. if (save_size>max_halfword)or(max_strings>max_halfword) then bad:=17;
  2067. if buf_size>max_halfword then bad:=18;
  2068. if max_quarterword-min_quarterword<255 then bad:=19;
  2069. @ The operation of adding or subtracting |min_quarterword| occurs quite
  2070. frequently in \TeX, so it is convenient to abbreviate this operation
  2071. by using the macros |qi| and |qo| for input and output to and from
  2072. quarterword format.
  2073. The inner loop of \TeX\ will run faster with respect to compilers
  2074. that don't optimize expressions like `|x+0|' and `|x-0|', if these
  2075. macros are simplified in the obvious way when |min_quarterword=0|.
  2076. @^inner loop@>@^system dependencies@>
  2077. @d qi(#)==#+min_quarterword
  2078.   {to put an |eight_bits| item into a quarterword}
  2079. @d qo(#)==#-min_quarterword
  2080.   {to take an |eight_bits| item out of a quarterword}
  2081. @d hi(#)==#+min_halfword
  2082.   {to put a sixteen-bit item into a halfword}
  2083. @d ho(#)==#-min_halfword
  2084.   {to take a sixteen-bit item from a halfword}
  2085. @ The reader should study the following definitions closely:
  2086. @^system dependencies@>
  2087. @d sc==int {|scaled| data is equivalent to |integer|}
  2088. @<Types...@>=
  2089. @!quarterword = min_quarterword..max_quarterword; {1/4 of a word}
  2090. @!halfword=min_halfword..max_halfword; {1/2 of a word}
  2091. @!two_choices = 1..2; {used when there are two variants in a record}
  2092. @!four_choices = 1..4; {used when there are four variants in a record}
  2093. @!two_halves = packed record@;@/
  2094.   @!rh:halfword;
  2095.   case two_choices of
  2096.   1: (@!lh:halfword);
  2097.   2: (@!b0:quarterword; @!b1:quarterword);
  2098.   end;
  2099. @!four_quarters = packed record@;@/
  2100.   @!b0:quarterword;
  2101.   @!b1:quarterword;
  2102.   @!b2:quarterword;
  2103.   @!b3:quarterword;
  2104.   end;
  2105. @!memory_word = record@;@/
  2106.   case four_choices of
  2107.   1: (@!int:integer);
  2108.   2: (@!gr:glue_ratio);
  2109.   3: (@!hh:two_halves);
  2110.   4: (@!qqqq:four_quarters);
  2111.   end;
  2112. @!word_file = file of memory_word;
  2113. @ When debugging, we may want to print a |memory_word| without knowing
  2114. what type it is; so we print it in all modes.
  2115. @^dirty \PASCAL@>@^debugging@>
  2116. @p @!debug procedure print_word(@!w:memory_word);
  2117.   {prints |w| in all ways}
  2118. begin print_int(w.int); print_char(" ");@/
  2119. print_scaled(w.sc); print_char(" ");@/
  2120. print_scaled(round(unity*float(w.gr))); print_ln;@/
  2121. @^real multiplication@>
  2122. print_int(w.hh.lh); print_char("="); print_int(w.hh.b0); print_char(":");
  2123. print_int(w.hh.b1); print_char(";"); print_int(w.hh.rh); print_char(" ");@/
  2124. print_int(w.qqqq.b0); print_char(":"); print_int(w.qqqq.b1); print_char(":");
  2125. print_int(w.qqqq.b2); print_char(":"); print_int(w.qqqq.b3);
  2126. gubed
  2127. @* \[9] Dynamic memory allocation.
  2128. The \TeX\ system does nearly all of its own memory allocation, so that it
  2129. can readily be transported into environments that do not have automatic
  2130. facilities for strings, garbage collection, etc., and so that it can be in
  2131. control of what error messages the user receives. The dynamic storage
  2132. requirements of \TeX\ are handled by providing a large array |mem| in
  2133. which consecutive blocks of words are used as nodes by the \TeX\ routines.
  2134. Pointer variables are indices into this array, or into another array
  2135. called |eqtb| that will be explained later. A pointer variable might
  2136. also be a special flag that lies outside the bounds of |mem|, so we
  2137. allow pointers to assume any |halfword| value. The minimum halfword
  2138. value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
  2139. @d pointer==halfword {a flag or a location in |mem| or |eqtb|}
  2140. @d null==min_halfword {the null pointer}
  2141. @<Glob...@>=
  2142. @!temp_ptr:pointer; {a pointer variable for occasional emergency use}
  2143. @ The |mem| array is divided into two regions that are allocated separately,
  2144. but the dividing line between these two regions is not fixed; they grow
  2145. together until finding their ``natural'' size in a particular job.
  2146. Locations less than or equal to |lo_mem_max| are used for storing
  2147. variable-length records consisting of two or more words each. This region
  2148. is maintained using an algorithm similar to the one described in exercise
  2149. 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
  2150. appears in the allocated nodes; the program is responsible for knowing the
  2151. relevant size when a node is freed. Locations greater than or equal to
  2152. |hi_mem_min| are used for storing one-word records; a conventional
  2153. \.{AVAIL} stack is used for allocation in this region.
  2154. Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
  2155. of preloaded format files, by the \.{INITEX} preprocessor.
  2156. @.INITEX@>
  2157. Production versions of \TeX\ may extend the memory at both ends in order to
  2158. provide more space; locations between |mem_min| and |mem_bot| are always
  2159. used for variable-size nodes, and locations between |mem_top| and |mem_max|
  2160. are always used for single-word nodes.
  2161. The key pointers that govern |mem| allocation have a prescribed order:
  2162. $$\advance\thickmuskip-2mu
  2163. \hbox{|null<=mem_min<=mem_bot<lo_mem_max<
  2164.   hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
  2165. Empirical tests show that the present implementation of \TeX\ tends to
  2166. spend about 9\pct! of its running time allocating nodes, and about 6\pct!
  2167. deallocating them after their use.
  2168. @<Glob...@>=
  2169. @!mem : array[mem_min..mem_max] of memory_word; {the big dynamic storage area}
  2170. @!lo_mem_max : pointer; {the largest location of variable-size memory in use}
  2171. @!hi_mem_min : pointer; {the smallest location of one-word memory in use}
  2172. @ In order to study the memory requirements of particular applications, it
  2173. is possible to prepare a version of \TeX\ that keeps track of current and
  2174. maximum memory usage. When code between the delimiters |@!stat| $\ldots$
  2175. |tats| is not ``commented out,'' \TeX\ will run a bit slower but it will
  2176. report these statistics when |tracing_stats| is sufficiently large.
  2177. @<Glob...@>=
  2178. @!var_used, @!dyn_used : integer; {how much memory is in use}
  2179. @ Let's consider the one-word memory region first, since it's the
  2180. simplest. The pointer variable |mem_end| holds the highest-numbered location
  2181. of |mem| that has ever been used. The free locations of |mem| that
  2182. occur between |hi_mem_min| and |mem_end|, inclusive, are of type
  2183. |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
  2184. and |rh| fields of |mem[p]| when it is of this type. The single-word
  2185. free locations form a linked list
  2186. $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
  2187. terminated by |null|.
  2188. @d link(#) == mem[#].hh.rh {the |link| field of a memory word}
  2189. @d info(#) == mem[#].hh.lh {the |info| field of a memory word}
  2190. @<Glob...@>=
  2191. @!avail : pointer; {head of the list of available one-word nodes}
  2192. @!mem_end : pointer; {the last one-word node used in |mem|}
  2193. @ If memory is exhausted, it might mean that the user has forgotten
  2194. a right brace. We will define some procedures later that try to help
  2195. pinpoint the trouble.
  2196. @p @<Declare the procedure called |show_token_list|@>@/
  2197. @<Declare the procedure called |runaway|@>
  2198. @ The function |get_avail| returns a pointer to a new one-word node whose
  2199. |link| field is null. However, \TeX\ will halt if there is no more room left.
  2200. @^inner loop@>
  2201. If the available-space list is empty, i.e., if |avail=null|,
  2202. we try first to increase |mem_end|. If that cannot be done, i.e., if
  2203. |mem_end=mem_max|, we try to decrease |hi_mem_min|. If that cannot be
  2204. done, i.e., if |hi_mem_min=lo_mem_max+1|, we have to quit.
  2205. @p function get_avail : pointer; {single-word node allocation}
  2206. var p:pointer; {the new node being got}
  2207. begin p:=avail; {get top location in the |avail| stack}
  2208. if p<>null then avail:=link(avail) {and pop it off}
  2209. else if mem_end<mem_max then {or go into virgin territory}
  2210.   begin incr(mem_end); p:=mem_end;
  2211.   end
  2212. else   begin decr(hi_mem_min); p:=hi_mem_min;
  2213.   if hi_mem_min<=lo_mem_max then
  2214.     begin runaway; {if memory is exhausted, display possible runaway text}
  2215.     overflow("main memory size",mem_max+1-mem_min);
  2216.       {quit; all one-word nodes are busy}
  2217. @:TeX capacity exceeded main memory size}{\quad main memory size@>
  2218.     end;
  2219.   end;
  2220. link(p):=null; {provide an oft-desired initialization of the new node}
  2221. @!stat incr(dyn_used);@+tats@;{maintain statistics}
  2222. get_avail:=p;
  2223. @ Conversely, a one-word node is recycled by calling |free_avail|.
  2224. This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
  2225. @^inner loop@>
  2226. @d free_avail(#)== {single-word node liberation}
  2227.   begin link(#):=avail; avail:=#;
  2228.   @!stat decr(dyn_used);@+tats@/
  2229.   end
  2230. @ There's also a |fast_get_avail| routine, which saves the procedure-call
  2231. overhead at the expense of extra programming. This routine is used in
  2232. the places that would otherwise account for the most calls of |get_avail|.
  2233. @^inner loop@>
  2234. @d fast_get_avail(#)==@t@>@;@/
  2235.   begin #:=avail; {avoid |get_avail| if possible, to save time}
  2236.   if #=null then #:=get_avail
  2237.   else  begin avail:=link(#); link(#):=null;
  2238.     @!stat incr(dyn_used);@+tats@/
  2239.     end;
  2240.   end
  2241. @ The procedure |flush_list(p)| frees an entire linked list of
  2242. one-word nodes that starts at position |p|.
  2243. @^inner loop@>
  2244. @p procedure flush_list(@!p:pointer); {makes list of single-word nodes
  2245.   available}
  2246. var @!q,@!r:pointer; {list traversers}
  2247. begin if p<>null then
  2248.   begin r:=p;
  2249.   repeat q:=r; r:=link(r); @!stat decr(dyn_used);@+tats@/
  2250.   until r=null; {now |q| is the last node on the list}
  2251.   link(q):=avail; avail:=p;
  2252.   end;
  2253. @ The available-space list that keeps track of the variable-size portion
  2254. of |mem| is a nonempty, doubly-linked circular list of empty nodes,
  2255. pointed to by the roving pointer |rover|.
  2256. Each empty node has size 2 or more; the first word contains the special
  2257. value |max_halfword| in its |link| field and the size in its |info| field;
  2258. the second word contains the two pointers for double linking.
  2259. Each nonempty node also has size 2 or more. Its first word is of type
  2260. |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
  2261. Otherwise there is complete flexibility with respect to the contents
  2262. of its other fields and its other words.
  2263. (We require |mem_max<max_halfword| because terrible things can happen
  2264. when |max_halfword| appears in the |link| field of a nonempty node.)
  2265. @d empty_flag == max_halfword {the |link| of an empty variable-size node}
  2266. @d is_empty(#) == (link(#)=empty_flag) {tests for empty node}
  2267. @d node_size == info {the size field in empty variable-size nodes}
  2268. @d llink(#) == info(#+1) {left link in doubly-linked list of empty nodes}
  2269. @d rlink(#) == link(#+1) {right link in doubly-linked list of empty nodes}
  2270. @<Glob...@>=
  2271. @!rover : pointer; {points to some node in the list of empties}
  2272. @ A call to |get_node| with argument |s| returns a pointer to a new node
  2273. of size~|s|, which must be 2~or more. The |link| field of the first word
  2274. of this new node is set to null. An overflow stop occurs if no suitable
  2275. space exists.
  2276. If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
  2277. areas and returns the value |max_halfword|.
  2278. @p function get_node(@!s:integer):pointer; {variable-size node allocation}
  2279. label found,exit,restart;
  2280. var p:pointer; {the node currently under inspection}
  2281. @!q:pointer; {the node physically after node |p|}
  2282. @!r:integer; {the newly allocated node, or a candidate for this honor}
  2283. @!t:integer; {temporary register}
  2284. begin restart: p:=rover; {start at some free node in the ring}
  2285. repeat @<Try to allocate within node |p| and its physical successors,
  2286.   and |goto found| if allocation was possible@>;
  2287. @^inner loop@>
  2288. p:=rlink(p); {move to the next node in the ring}
  2289. until p=rover; {repeat until the whole list has been traversed}
  2290. if s=@'10000000000 then
  2291.   begin get_node:=max_halfword; return;
  2292.   end;
  2293. if lo_mem_max+2<hi_mem_min then if lo_mem_max+2<=mem_bot+max_halfword then
  2294.   @<Grow more variable-size memory and |goto restart|@>;
  2295. overflow("main memory size",mem_max+1-mem_min);
  2296.   {sorry, nothing satisfactory is left}
  2297. @:TeX capacity exceeded main memory size}{\quad main memory size@>
  2298. found: link(r):=null; {this node is now nonempty}
  2299. @!stat var_used:=var_used+s; {maintain usage statistics}
  2300. tats@;@/
  2301. get_node:=r;
  2302. exit:end;
  2303. @ The lower part of |mem| grows by 1000 words at a time, unless
  2304. we are very close to going under. When it grows, we simply link
  2305. a new node into the available-space list. This method of controlled
  2306. growth helps to keep the |mem| usage consecutive when \TeX\ is
  2307. implemented on ``virtual memory'' systems.
  2308. @^virtual memory@>
  2309. @<Grow more variable-size memory and |goto restart|@>=
  2310. begin if hi_mem_min-lo_mem_max>=1998 then t:=lo_mem_max+1000
  2311. else t:=lo_mem_max+1+(hi_mem_min-lo_mem_max) div 2;
  2312.   {|lo_mem_max+2<=t<hi_mem_min|}
  2313. p:=llink(rover); q:=lo_mem_max; rlink(p):=q; llink(rover):=q;@/
  2314. if t>mem_bot+max_halfword then t:=mem_bot+max_halfword;
  2315. rlink(q):=rover; llink(q):=p; link(q):=empty_flag; node_size(q):=t-lo_mem_max;@/
  2316. lo_mem_max:=t; link(lo_mem_max):=null; info(lo_mem_max):=null;
  2317. rover:=q; goto restart;
  2318. @ Empirical tests show that the routine in this section performs a
  2319. node-merging operation about 0.75 times per allocation, on the average,
  2320. after which it finds that |r>p+1| about 95\pct! of the time.
  2321. @<Try to allocate...@>=
  2322. q:=p+node_size(p); {find the physical successor}
  2323. @^inner loop@>
  2324. while is_empty(q) do {merge node |p| with node |q|}
  2325.   begin t:=rlink(q);
  2326.   if q=rover then rover:=t;
  2327.   llink(t):=llink(q); rlink(llink(q)):=t;@/
  2328.   q:=q+node_size(q);
  2329.   end;
  2330. r:=q-s;
  2331. if r>p+1 then @<Allocate from the top of node |p| and |goto found|@>;
  2332. if r=p then if rlink(p)<>p then
  2333.   @<Allocate entire node |p| and |goto found|@>;
  2334. node_size(p):=q-p {reset the size in case it grew}
  2335. @ @<Allocate from the top...@>=
  2336. begin node_size(p):=r-p; {store the remaining size}
  2337. @^inner loop@>
  2338. rover:=p; {start searching here next time}
  2339. goto found;
  2340. @ Here we delete node |p| from the ring, and let |rover| rove around.
  2341. @<Allocate entire...@>=
  2342. begin rover:=rlink(p); t:=llink(p);
  2343. llink(rover):=t; rlink(t):=rover;
  2344. goto found;
  2345. @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
  2346. the operation |free_node(p,s)| will make its words available, by inserting
  2347. |p| as a new empty node just before where |rover| now points.
  2348. @^inner loop@>
  2349. @p procedure free_node(@!p:pointer; @!s:halfword); {variable-size node
  2350.   liberation}
  2351. var q:pointer; {|llink(rover)|}
  2352. begin node_size(p):=s; link(p):=empty_flag;
  2353. q:=llink(rover); llink(p):=q; rlink(p):=rover; {set both links}
  2354. llink(rover):=p; rlink(q):=p; {insert |p| into the ring}
  2355. @!stat var_used:=var_used-s;@+tats@;{maintain statistics}
  2356. @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
  2357. available space list. The list is probably very short at such times, so a
  2358. simple insertion sort is used. The smallest available location will be
  2359. pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
  2360. @p @!init procedure sort_avail; {sorts the available variable-size nodes
  2361.   by location}
  2362. var p,@!q,@!r: pointer; {indices into |mem|}
  2363. @!old_rover:pointer; {initial |rover| setting}
  2364. begin p:=get_node(@'10000000000); {merge adjacent free areas}
  2365. p:=rlink(rover); rlink(rover):=max_halfword; old_rover:=rover;
  2366. while p<>old_rover do @<Sort \(p)|p| into the list starting at |rover|
  2367.   and advance |p| to |rlink(p)|@>;
  2368. p:=rover;
  2369. while rlink(p)<>max_halfword do
  2370.   begin llink(rlink(p)):=p; p:=rlink(p);
  2371.   end;
  2372. rlink(p):=rover; llink(rover):=p;
  2373. @ The following |while| loop is guaranteed to
  2374. terminate, since the list that starts at
  2375. |rover| ends with |max_halfword| during the sorting procedure.
  2376. @<Sort \(p)|p|...@>=
  2377. if p<rover then
  2378.   begin q:=p; p:=rlink(q); rlink(q):=rover; rover:=q;
  2379.   end
  2380. else  begin q:=rover;
  2381.   while rlink(q)<p do q:=rlink(q);
  2382.   r:=rlink(p); rlink(p):=rlink(q); rlink(q):=p; p:=r;
  2383.   end
  2384. @* \[10] Data structures for boxes and their friends.
  2385. From the computer's standpoint, \TeX's chief mission is to create
  2386. horizontal and vertical lists. We shall now investigate how the elements
  2387. of these lists are represented internally as nodes in the dynamic memory.
  2388. A horizontal or vertical list is linked together by |link| fields in
  2389. the first word of each node. Individual nodes represent boxes, glue,
  2390. penalties, or special things like discretionary hyphens; because of this
  2391. variety, some nodes are longer than others, and we must distinguish different
  2392. kinds of nodes. We do this by putting a `|type|' field in the first word,
  2393. together with the link and an optional `|subtype|'.
  2394. @d type(#) == mem[#].hh.b0 {identifies what kind of node this is}
  2395. @d subtype(#) == mem[#].hh.b1 {secondary identification in some cases}
  2396. @ A |@!char_node|, which represents a single character, is the most important
  2397. kind of node because it accounts for the vast majority of all boxes.
  2398. Special precautions are therefore taken to ensure that a |char_node| does
  2399. not take up much memory space. Every such node is one word long, and in fact
  2400. it is identifiable by this property, since other kinds of nodes have at least
  2401. two words, and they appear in |mem| locations less than |hi_mem_min|.
  2402. This makes it possible to omit the |type| field in a |char_node|, leaving
  2403. us room for two bytes that identify a |font| and a |character| within
  2404. that font.
  2405. Note that the format of a |char_node| allows for up to 256 different
  2406. fonts and up to 256 characters per font; but most implementations will
  2407. probably limit the total number of fonts to fewer than 75 per job,
  2408. and most fonts will stick to characters whose codes are
  2409. less than 128 (since higher codes
  2410. are more difficult to access on most keyboards).
  2411. Extensions of \TeX\ intended for oriental languages will need even more
  2412. than $256\times256$ possible characters, when we consider different sizes
  2413. @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
  2414. and styles of type.  It is suggested that Chinese and Japanese fonts be
  2415. handled by representing such characters in two consecutive |char_node|
  2416. entries: The first of these has |font=font_base|, and its |link| points
  2417. to the second;
  2418. the second identifies the font and the character dimensions.
  2419. The saving feature about oriental characters is that most of them have
  2420. the same box dimensions. The |character| field of the first |char_node|
  2421. is a ``\\{charext}'' that distinguishes between graphic symbols whose
  2422. dimensions are identical for typesetting purposes. (See the \MF\ manual.)
  2423. Such an extension of \TeX\ would not be difficult; further details are
  2424. left to the reader.
  2425. In order to make sure that the |character| code fits in a quarterword,
  2426. \TeX\ adds the quantity |min_quarterword| to the actual code.
  2427. Character nodes appear only in horizontal lists, never in vertical lists.
  2428. @d is_char_node(#) == (#>=hi_mem_min)
  2429.   {does the argument point to a |char_node|?}
  2430. @d font == type {the font code in a |char_node|}
  2431. @d character == subtype {the character code in a |char_node|}
  2432. @ An |hlist_node| stands for a box that was made from a horizontal list.
  2433. Each |hlist_node| is seven words long, and contains the following fields
  2434. (in addition to the mandatory |type| and |link|, which we shall not
  2435. mention explicitly when discussing the other node types): The |height| and
  2436. |width| and |depth| are scaled integers denoting the dimensions of the
  2437. box.  There is also a |shift_amount| field, a scaled integer indicating
  2438. how much this box should be lowered (if it appears in a horizontal list),
  2439. or how much it should be moved to the right (if it appears in a vertical
  2440. list). There is a |list_ptr| field, which points to the beginning of the
  2441. list from which this box was fabricated; if |list_ptr| is |null|, the box
  2442. is empty. Finally, there are three fields that represent the setting of
  2443. the glue:  |glue_set(p)| is a word of type |glue_ratio| that represents
  2444. the proportionality constant for glue setting; |glue_sign(p)| is
  2445. |stretching| or |shrinking| or |normal| depending on whether or not the
  2446. glue should stretch or shrink or remain rigid; and |glue_order(p)|
  2447. specifies the order of infinity to which glue setting applies (|normal|,
  2448. |fil|, |fill|, or |filll|). The |subtype| field is not used.
  2449. @d hlist_node=0 {|type| of hlist nodes}
  2450. @d box_node_size=7 {number of words to allocate for a box node}
  2451. @d width_offset=1 {position of |width| field in a box node}
  2452. @d depth_offset=2 {position of |depth| field in a box node}
  2453. @d height_offset=3 {position of |height| field in a box node}
  2454. @d width(#) == mem[#+width_offset].sc {width of the box, in sp}
  2455. @d depth(#) == mem[#+depth_offset].sc {depth of the box, in sp}
  2456. @d height(#) == mem[#+height_offset].sc {height of the box, in sp}
  2457. @d shift_amount(#) == mem[#+4].sc {repositioning distance, in sp}
  2458. @d list_offset=5 {position of |list_ptr| field in a box node}
  2459. @d list_ptr(#) == link(#+list_offset) {beginning of the list inside the box}
  2460. @d glue_order(#) == subtype(#+list_offset) {applicable order of infinity}
  2461. @d glue_sign(#) == type(#+list_offset) {stretching or shrinking}
  2462. @d normal=0 {the most common case when several cases are named}
  2463. @d stretching = 1 {glue setting applies to the stretch components}
  2464. @d shrinking = 2 {glue setting applies to the shrink components}
  2465. @d glue_offset = 6 {position of |glue_set| in a box node}
  2466. @d glue_set(#) == mem[#+glue_offset].gr
  2467.   {a word of type |glue_ratio| for glue setting}
  2468. @ The |new_null_box| function returns a pointer to an |hlist_node| in
  2469. which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
  2470. The |subtype| field is set to |min_quarterword|, since that's the desired
  2471. |span_count| value if this |hlist_node| is changed to an |unset_node|.
  2472. @p function new_null_box:pointer; {creates a new box node}
  2473. var p:pointer; {the new node}
  2474. begin p:=get_node(box_node_size); type(p):=hlist_node;
  2475. subtype(p):=min_quarterword;
  2476. width(p):=0; depth(p):=0; height(p):=0; shift_amount(p):=0; list_ptr(p):=null;
  2477. glue_sign(p):=normal; glue_order(p):=normal; set_glue_ratio_zero(glue_set(p));
  2478. new_null_box:=p;
  2479. @ A |vlist_node| is like an |hlist_node| in all respects except that it
  2480. contains a vertical list.
  2481. @d vlist_node=1 {|type| of vlist nodes}
  2482. @ A |rule_node| stands for a solid black rectangle; it has |width|,
  2483. |depth|, and |height| fields just as in an |hlist_node|. However, if
  2484. any of these dimensions is $-2^{30}$, the actual value will be determined
  2485. by running the rule up to the boundary of the innermost enclosing box.
  2486. This is called a ``running dimension.'' The |width| is never running in
  2487. an hlist; the |height| and |depth| are never running in a~vlist.
  2488. @d rule_node=2 {|type| of rule nodes}
  2489. @d rule_node_size=4 {number of words to allocate for a rule node}
  2490. @d null_flag==-@'10000000000 {$-2^{30}$, signifies a missing item}
  2491. @d is_running(#) == (#=null_flag) {tests for a running dimension}
  2492. @ A new rule node is delivered by the |new_rule| function. It
  2493. makes all the dimensions ``running,'' so you have to change the
  2494. ones that are not allowed to run.
  2495. @p function new_rule:pointer;
  2496. var p:pointer; {the new node}
  2497. begin p:=get_node(rule_node_size); type(p):=rule_node;
  2498. subtype(p):=0; {the |subtype| is not used}
  2499. width(p):=null_flag; depth(p):=null_flag; height(p):=null_flag;
  2500. new_rule:=p;
  2501. @ Insertions are represented by |ins_node| records, where the |subtype|
  2502. indicates the corresponding box number. For example, `\.{\\insert 250}'
  2503. leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
  2504. The |height| field of an |ins_node| is slightly misnamed; it actually holds
  2505. the natural height plus depth of the vertical list being inserted.
  2506. The |depth| field holds the |split_max_depth| to be used in case this
  2507. insertion is split, and the |split_top_ptr| points to the corresponding
  2508. |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
  2509. will be used if this insertion floats to a subsequent page after a
  2510. split insertion of the same class.  There is one more field, the
  2511. |ins_ptr|, which points to the beginning of the vlist for the insertion.
  2512. @d ins_node=3 {|type| of insertion nodes}
  2513. @d ins_node_size=5 {number of words to allocate for an insertion}
  2514. @d float_cost(#)==mem[#+1].int {the |floating_penalty| to be used}
  2515. @d ins_ptr(#)==info(#+4) {the vertical list to be inserted}
  2516. @d split_top_ptr(#)==link(#+4) {the |split_top_skip| to be used}
  2517. @ A |mark_node| has a |mark_ptr| field that points to the reference count
  2518. of a token list that contains the user's \.{\\mark} text.
  2519. This field occupies a full word instead of a halfword, because
  2520. there's nothing to put in the other halfword; it is easier in \PASCAL\ to
  2521. use the full word than to risk leaving garbage in the unused half.
  2522. @d mark_node=4 {|type| of a mark node}
  2523. @d small_node_size=2 {number of words to allocate for most node types}
  2524. @d mark_ptr(#)==mem[#+1].int {head of the token list for a mark}
  2525. @ An |adjust_node|, which occurs only in horizontal lists,
  2526. specifies material that will be moved out into the surrounding
  2527. vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
  2528. operation.  The |adjust_ptr| field points to the vlist containing this
  2529. material.
  2530. @d adjust_node=5 {|type| of an adjust node}
  2531. @d adjust_ptr==mark_ptr {vertical list to be moved out of horizontal list}
  2532. @ A |ligature_node|, which occurs only in horizontal lists, specifies
  2533. a character that was fabricated from the interaction of two or more
  2534. actual characters.  The second word of the node, which is called the
  2535. |lig_char| word, contains |font| and |character| fields just as in a
  2536. |char_node|. The characters that generated the ligature have not been
  2537. forgotten, since they are needed for diagnostic messages and for
  2538. hyphenation; the |lig_ptr| field points to a linked list of character
  2539. nodes for all original characters that have been deleted. (This list
  2540. might be empty if the characters that generated the ligature were
  2541. retained in other nodes.)
  2542. The |subtype| field is 0, plus 2 and/or 1 if the original source of the
  2543. ligature included implicit left and/or right boundaries.
  2544. @d ligature_node=6 {|type| of a ligature node}
  2545. @d lig_char(#)==#+1 {the word where the ligature is to be found}
  2546. @d lig_ptr(#)==link(lig_char(#)) {the list of characters}
  2547. @ The |new_ligature| function creates a ligature node having given
  2548. contents of the |font|, |character|, and |lig_ptr| fields. We also have
  2549. a |new_lig_item| function, which returns a two-word node having a given
  2550. |character| field. Such nodes are used for temporary processing as ligatures
  2551. are being created.
  2552. @p function new_ligature(@!f,@!c:quarterword; @!q:pointer):pointer;
  2553. var p:pointer; {the new node}
  2554. begin p:=get_node(small_node_size); type(p):=ligature_node;
  2555. font(lig_char(p)):=f; character(lig_char(p)):=c; lig_ptr(p):=q;
  2556. subtype(p):=0; new_ligature:=p;
  2557. function new_lig_item(@!c:quarterword):pointer;
  2558. var p:pointer; {the new node}
  2559. begin p:=get_node(small_node_size); character(p):=c; lig_ptr(p):=null;
  2560. new_lig_item:=p;
  2561. @ A |disc_node|, which occurs only in horizontal lists, specifies a
  2562. ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
  2563. that starts at |pre_break(p)| will precede the break, the text that starts at
  2564. |post_break(p)| will follow the break, and text that appears in the next
  2565. |replace_count(p)| nodes will be ignored. For example, an ordinary
  2566. discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
  2567. |pre_break| pointing to a |char_node| containing a hyphen, |post_break=null|,
  2568. and |replace_count=0|. All three of the discretionary texts must be
  2569. lists that consist entirely of character, kern, box, rule, and ligature nodes.
  2570. If |pre_break(p)=null|, the |ex_hyphen_penalty| will be charged for this
  2571. break.  Otherwise the |hyphen_penalty| will be charged.  The texts will
  2572. actually be substituted into the list by the line-breaking algorithm if it
  2573. decides to make the break, and the discretionary node will disappear at
  2574. that time; thus, the output routine sees only discretionaries that were
  2575. not chosen.
  2576. @d disc_node=7 {|type| of a discretionary node}
  2577. @d replace_count==subtype {how many subsequent nodes to replace}
  2578. @d pre_break==llink {text that precedes a discretionary break}
  2579. @d post_break==rlink {text that follows a discretionary break}
  2580. @p function new_disc:pointer; {creates an empty |disc_node|}
  2581. var p:pointer; {the new node}
  2582. begin p:=get_node(small_node_size); type(p):=disc_node;
  2583. replace_count(p):=0; pre_break(p):=null; post_break(p):=null;
  2584. new_disc:=p;
  2585. @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
  2586. |subtype| field in its first word says what `\\{whatsit}' it is, and
  2587. implicitly determines the node size (which must be 2 or more) and the
  2588. format of the remaining words. When a |whatsit_node| is encountered
  2589. in a list, special actions are invoked; knowledgeable people who are
  2590. careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
  2591. things by adding code at the end of the program. For example, there
  2592. might be a `\TeX nicolor' extension to specify different colors of ink,
  2593. @^extensions to \TeX@>
  2594. and the whatsit node might contain the desired parameters.
  2595. The present implementation of \TeX\ treats the features associated with
  2596. `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
  2597. illustrate how such routines might be coded. We shall defer further
  2598. discussion of extensions until the end of this program.
  2599. @d whatsit_node=8 {|type| of special extension nodes}
  2600. @ A |math_node|, which occurs only in horizontal lists, appears before and
  2601. after mathematical formulas. The |subtype| field is |before| before the
  2602. formula and |after| after it. There is a |width| field, which represents
  2603. the amount of surrounding space inserted by \.{\\mathsurround}.
  2604. @d math_node=9 {|type| of a math node}
  2605. @d before=0 {|subtype| for math node that introduces a formula}
  2606. @d after=1 {|subtype| for math node that winds up a formula}
  2607. @p function new_math(@!w:scaled;@!s:small_number):pointer;
  2608. var p:pointer; {the new node}
  2609. begin p:=get_node(small_node_size); type(p):=math_node;
  2610. subtype(p):=s; width(p):=w; new_math:=p;
  2611. @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
  2612. |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
  2613. |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
  2614. type codes, by permitting a break at glue in a list if and only if the
  2615. |type| of the previous node is less than |math_node|. Furthermore, a
  2616. node is discarded after a break if its type is |math_node| or~more.
  2617. @d precedes_break(#)==(type(#)<math_node)
  2618. @d non_discardable(#)==(type(#)<math_node)
  2619. @ A |glue_node| represents glue in a list. However, it is really only
  2620. a pointer to a separate glue specification, since \TeX\ makes use of the
  2621. fact that many essentially identical nodes of glue are usually present.
  2622. If |p| points to a |glue_node|, |glue_ptr(p)| points to
  2623. another packet of words that specify the stretch and shrink components, etc.
  2624. Glue nodes also serve to represent leaders; the |subtype| is used to
  2625. distinguish between ordinary glue (which is called |normal|) and the three
  2626. kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
  2627. The |leader_ptr| field points to a rule node or to a box node containing the
  2628. leaders; it is set to |null| in ordinary glue nodes.
  2629. Many kinds of glue are computed from \TeX's ``skip'' parameters, and
  2630. it is helpful to know which parameter has led to a particular glue node.
  2631. Therefore the |subtype| is set to indicate the source of glue, whenever
  2632. it originated as a parameter. We will be defining symbolic names for the
  2633. parameter numbers later (e.g., |line_skip_code=0|, |baseline_skip_code=1|,
  2634. etc.); it suffices for now to say that the |subtype| of parametric glue
  2635. will be the same as the parameter number, plus~one.
  2636. In math formulas there are two more possibilities for the |subtype| in a
  2637. glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
  2638. instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
  2639. feature that cancels the glue node immediately following if it appears
  2640. in a subscript.
  2641. @d glue_node=10 {|type| of node that points to a glue specification}
  2642. @d cond_math_glue=98 {special |subtype| to suppress glue in the next node}
  2643. @d mu_glue=99 {|subtype| for math glue}
  2644. @d a_leaders=100 {|subtype| for aligned leaders}
  2645. @d c_leaders=101 {|subtype| for centered leaders}
  2646. @d x_leaders=102 {|subtype| for expanded leaders}
  2647. @d glue_ptr==llink {pointer to a glue specification}
  2648. @d leader_ptr==rlink {pointer to box or rule node for leaders}
  2649. @ A glue specification has a halfword reference count in its first word,
  2650. @^reference counts@>
  2651. representing |null| plus the number of glue nodes that point to it (less one).
  2652. Note that the reference count appears in the same position as
  2653. the |link| field in list nodes; this is the field that is initialized
  2654. to |null| when a node is allocated, and it is also the field that is flagged
  2655. by |empty_flag| in empty nodes.
  2656. Glue specifications also contain three |scaled| fields, for the |width|,
  2657. |stretch|, and |shrink| dimensions. Finally, there are two one-byte
  2658. fields called |stretch_order| and |shrink_order|; these contain the
  2659. orders of infinity (|normal|, |fil|, |fill|, or |filll|)
  2660. corresponding to the stretch and shrink values.
  2661. @d glue_spec_size=4 {number of words to allocate for a glue specification}
  2662. @d glue_ref_count(#) == link(#) {reference count of a glue specification}
  2663. @d stretch(#) == mem[#+2].sc {the stretchability of this glob of glue}
  2664. @d shrink(#) == mem[#+3].sc {the shrinkability of this glob of glue}
  2665. @d stretch_order == type {order of infinity for stretching}
  2666. @d shrink_order == subtype {order of infinity for shrinking}
  2667. @d fil=1 {first-order infinity}
  2668. @d fill=2 {second-order infinity}
  2669. @d filll=3 {third-order infinity}
  2670. @<Types...@>=
  2671. @!glue_ord=normal..filll; {infinity to the 0, 1, 2, or 3 power}
  2672. @ Here is a function that returns a pointer to a copy of a glue spec.
  2673. The reference count in the copy is |null|, because there is assumed
  2674. to be exactly one reference to the new specification.
  2675. @p function new_spec(@!p:pointer):pointer; {duplicates a glue specification}
  2676. var q:pointer; {the new spec}
  2677. begin q:=get_node(glue_spec_size);@/
  2678. mem[q]:=mem[p]; glue_ref_count(q):=null;@/
  2679. width(q):=width(p); stretch(q):=stretch(p); shrink(q):=shrink(p);
  2680. new_spec:=q;
  2681. @ And here's a function that creates a glue node for a given parameter
  2682. identified by its code number; for example,
  2683. |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
  2684. current \.{\\lineskip}.
  2685. @p function new_param_glue(@!n:small_number):pointer;
  2686. var p:pointer; {the new node}
  2687. @!q:pointer; {the glue specification}
  2688. begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=n+1;
  2689. leader_ptr(p):=null;@/
  2690. q:=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
  2691. glue_ptr(p):=q; incr(glue_ref_count(q));
  2692. new_param_glue:=p;
  2693. @ Glue nodes that are more or less anonymous are created by |new_glue|,
  2694. whose argument points to a glue specification.
  2695. @p function new_glue(@!q:pointer):pointer;
  2696. var p:pointer; {the new node}
  2697. begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=normal;
  2698. leader_ptr(p):=null; glue_ptr(p):=q; incr(glue_ref_count(q));
  2699. new_glue:=p;
  2700. @ Still another subroutine is needed: this one is sort of a combination
  2701. of |new_param_glue| and |new_glue|. It creates a glue node for one of
  2702. the current glue parameters, but it makes a fresh copy of the glue
  2703. specification, since that specification will probably be subject to change,
  2704. while the parameter will stay put. The global variable |temp_ptr| is
  2705. set to the address of the new spec.
  2706. @p function new_skip_param(@!n:small_number):pointer;
  2707. var p:pointer; {the new node}
  2708. begin temp_ptr:=new_spec(@<Current |mem| equivalent of glue parameter...@>);
  2709. p:=new_glue(temp_ptr); glue_ref_count(temp_ptr):=null; subtype(p):=n+1;
  2710. new_skip_param:=p;
  2711. @ A |kern_node| has a |width| field to specify a (normally negative)
  2712. amount of spacing. This spacing correction appears in horizontal lists
  2713. between letters like A and V when the font designer said that it looks
  2714. better to move them closer together or further apart. A kern node can
  2715. also appear in a vertical list, when its `|width|' denotes additional
  2716. spacing in the vertical direction. The |subtype| is either |normal| (for
  2717. kerns inserted from font information or math mode calculations) or |explicit|
  2718. (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
  2719. (for kerns inserted from non-math accents) or |mu_glue| (for kerns
  2720. inserted from \.{\\mkern} specifications in math formulas).
  2721. @d kern_node=11 {|type| of a kern node}
  2722. @d explicit=1 {|subtype| of kern nodes from \.{\\kern} and \.{\\/}}
  2723. @d acc_kern=2 {|subtype| of kern nodes from accents}
  2724. @ The |new_kern| function creates a kern node having a given width.
  2725. @p function new_kern(@!w:scaled):pointer;
  2726. var p:pointer; {the new node}
  2727. begin p:=get_node(small_node_size); type(p):=kern_node;
  2728. subtype(p):=normal;
  2729. width(p):=w;
  2730. new_kern:=p;
  2731. @ A |penalty_node| specifies the penalty associated with line or page
  2732. breaking, in its |penalty| field. This field is a fullword integer, but
  2733. the full range of integer values is not used: Any penalty |>=10000| is
  2734. treated as infinity, and no break will be allowed for such high values.
  2735. Similarly, any penalty |<=-10000| is treated as negative infinity, and a
  2736. break will be forced.
  2737. @d penalty_node=12 {|type| of a penalty node}
  2738. @d inf_penalty=inf_bad {``infinite'' penalty value}
  2739. @d eject_penalty=-inf_penalty {``negatively infinite'' penalty value}
  2740. @d penalty(#) == mem[#+1].int {the added cost of breaking a list here}
  2741. @ Anyone who has been reading the last few sections of the program will
  2742. be able to guess what comes next.
  2743. @p function new_penalty(@!m:integer):pointer;
  2744. var p:pointer; {the new node}
  2745. begin p:=get_node(small_node_size); type(p):=penalty_node;
  2746. subtype(p):=0; {the |subtype| is not used}
  2747. penalty(p):=m; new_penalty:=p;
  2748. @ You might think that we have introduced enough node types by now. Well,
  2749. almost, but there is one more: An |unset_node| has nearly the same format
  2750. as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
  2751. or \.{\\valign} that are not yet in their final form, since the box
  2752. dimensions are their ``natural'' sizes before any glue adjustment has been
  2753. made. The |glue_set| word is not present; instead, we have a |glue_stretch|
  2754. field, which contains the total stretch of order |glue_order| that is
  2755. present in the hlist or vlist being boxed.
  2756. Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
  2757. containing the total shrink of order |glue_sign| that is present.
  2758. The |subtype| field is called |span_count|; an unset box typically
  2759. contains the data for |qo(span_count)+1| columns.
  2760. Unset nodes will be changed to box nodes when alignment is completed.
  2761. @d unset_node=13 {|type| for an unset node}
  2762. @d glue_stretch(#)==mem[#+glue_offset].sc {total stretch in an unset node}
  2763. @d glue_shrink==shift_amount {total shrink in an unset node}
  2764. @d span_count==subtype {indicates the number of spanned columns}
  2765. @ In fact, there are still more types coming. When we get to math formula
  2766. processing we will see that a |style_node| has |type=14|; and a number
  2767. of larger type codes will also be defined, for use in math mode only.
  2768. @ Warning: If any changes are made to these data structure layouts, such as
  2769. changing any of the node sizes or even reordering the words of nodes,
  2770. the |copy_node_list| procedure and the memory initialization code
  2771. below may have to be changed. Such potentially dangerous parts of the
  2772. program are listed in the index under `data structure assumptions'.
  2773. @!@^data structure assumptions@>
  2774. However, other references to the nodes are made symbolically in terms of
  2775. the \.{WEB} macro definitions above, so that format changes will leave
  2776. \TeX's other algorithms intact.
  2777. @^system dependencies@>
  2778. @* \[11] Memory layout.
  2779. Some areas of |mem| are dedicated to fixed usage, since static allocation is
  2780. more efficient than dynamic allocation when we can get away with it. For
  2781. example, locations |mem_bot| to |mem_bot+3| are always used to store the
  2782. specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
  2783. following macro definitions accomplish the static allocation by giving
  2784. symbolic names to the fixed positions. Static variable-size nodes appear
  2785. in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
  2786. appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
  2787. harmless to let |lig_trick| and |garbage| share the same location of |mem|.
  2788. @d zero_glue==mem_bot {specification for \.{0pt plus 0pt minus 0pt}}
  2789. @d fil_glue==zero_glue+glue_spec_size {\.{0pt plus 1fil minus 0pt}}
  2790. @d fill_glue==fil_glue+glue_spec_size {\.{0pt plus 1fill minus 0pt}}
  2791. @d ss_glue==fill_glue+glue_spec_size {\.{0pt plus 1fil minus 1fil}}
  2792. @d fil_neg_glue==ss_glue+glue_spec_size {\.{0pt plus -1fil minus 0pt}}
  2793. @d lo_mem_stat_max==fil_neg_glue+glue_spec_size-1 {largest statically
  2794.   allocated word in the variable-size |mem|}
  2795. @d page_ins_head==mem_top {list of insertion data for current page}
  2796. @d contrib_head==mem_top-1 {vlist of items not yet on current page}
  2797. @d page_head==mem_top-2 {vlist for current page}
  2798. @d temp_head==mem_top-3 {head of a temporary list of some kind}
  2799. @d hold_head==mem_top-4 {head of a temporary list of another kind}
  2800. @d adjust_head==mem_top-5 {head of adjustment list returned by |hpack|}
  2801. @d active==mem_top-7 {head of active list in |line_break|, needs two words}
  2802. @d align_head==mem_top-8 {head of preamble list for alignments}
  2803. @d end_span==mem_top-9 {tail of spanned-width lists}
  2804. @d omit_template==mem_top-10 {a constant token list}
  2805. @d null_list==mem_top-11 {permanently empty list}
  2806. @d lig_trick==mem_top-12 {a ligature masquerading as a |char_node|}
  2807. @d garbage==mem_top-12 {used for scrap information}
  2808. @d backup_head==mem_top-13 {head of token list built by |scan_keyword|}
  2809. @d hi_mem_stat_min==mem_top-13 {smallest statically allocated word in
  2810.   the one-word |mem|}
  2811. @d hi_mem_stat_usage=14 {the number of one-word nodes always present}
  2812. @ The following code gets |mem| off to a good start, when \TeX\ is
  2813. initializing itself the slow~way.
  2814. @<Local variables for init...@>=
  2815. @!k:integer; {index into |mem|, |eqtb|, etc.}
  2816. @ @<Initialize table entries...@>=
  2817. for k:=mem_bot+1 to lo_mem_stat_max do mem[k].sc:=0;
  2818.   {all glue dimensions are zeroed}
  2819. @^data structure assumptions@>
  2820. k:=mem_bot;@+while k<=lo_mem_stat_max do
  2821.     {set first words of glue specifications}
  2822.   begin glue_ref_count(k):=null+1;
  2823.   stretch_order(k):=normal; shrink_order(k):=normal;
  2824.   k:=k+glue_spec_size;
  2825.   end;
  2826. stretch(fil_glue):=unity; stretch_order(fil_glue):=fil;@/
  2827. stretch(fill_glue):=unity; stretch_order(fill_glue):=fill;@/
  2828. stretch(ss_glue):=unity; stretch_order(ss_glue):=fil;@/
  2829. shrink(ss_glue):=unity; shrink_order(ss_glue):=fil;@/
  2830. stretch(fil_neg_glue):=-unity; stretch_order(fil_neg_glue):=fil;@/
  2831. rover:=lo_mem_stat_max+1;
  2832. link(rover):=empty_flag; {now initialize the dynamic memory}
  2833. node_size(rover):=1000; {which is a 1000-word available node}
  2834. llink(rover):=rover; rlink(rover):=rover;@/
  2835. lo_mem_max:=rover+1000; link(lo_mem_max):=null; info(lo_mem_max):=null;@/
  2836. for k:=hi_mem_stat_min to mem_top do
  2837.   mem[k]:=mem[lo_mem_max]; {clear list heads}
  2838. @<Initialize the special list heads and constant nodes@>;
  2839. avail:=null; mem_end:=mem_top;
  2840. hi_mem_min:=hi_mem_stat_min; {initialize the one-word memory}
  2841. var_used:=lo_mem_stat_max+1-mem_bot; dyn_used:=hi_mem_stat_usage;
  2842.   {initialize statistics}
  2843. @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
  2844. For example, some pointers might be wrong, or some ``dead'' nodes might not
  2845. have been freed when the last reference to them disappeared. Procedures
  2846. |check_mem| and |search_mem| are available to help diagnose such
  2847. problems. These procedures make use of two arrays called |free| and
  2848. |was_free| that are present only if \TeX's debugging routines have
  2849. been included. (You may want to decrease the size of |mem| while you
  2850. @^debugging@>
  2851. are debugging.)
  2852. @<Glob...@>=
  2853. @!debug @!free: packed array [mem_min..mem_max] of boolean; {free cells}
  2854. @t\hskip10pt@>@!was_free: packed array [mem_min..mem_max] of boolean;
  2855.   {previously free cells}
  2856. @t\hskip10pt@>@!was_mem_end,@!was_lo_max,@!was_hi_min: pointer;
  2857.   {previous |mem_end|, |lo_mem_max|, and |hi_mem_min|}
  2858. @t\hskip10pt@>@!panicking:boolean; {do we want to check memory constantly?}
  2859. gubed
  2860. @ @<Set initial...@>=
  2861. @!debug was_mem_end:=mem_min; {indicate that everything was previously free}
  2862. was_lo_max:=mem_min; was_hi_min:=mem_max;
  2863. panicking:=false;
  2864. gubed
  2865. @ Procedure |check_mem| makes sure that the available space lists of
  2866. |mem| are well formed, and it optionally prints out all locations
  2867. that are reserved now but were free the last time this procedure was called.
  2868. @p @!debug procedure check_mem(@!print_locs : boolean);
  2869. label done1,done2; {loop exits}
  2870. var p,@!q:pointer; {current locations of interest in |mem|}
  2871. @!clobbered:boolean; {is something amiss?}
  2872. begin for p:=mem_min to lo_mem_max do free[p]:=false; {you can probably
  2873.   do this faster}
  2874. for p:=hi_mem_min to mem_end do free[p]:=false; {ditto}
  2875. @<Check single-word |avail| list@>;
  2876. @<Check variable-size |avail| list@>;
  2877. @<Check flags of unavailable nodes@>;
  2878. if print_locs then @<Print newly busy locations@>;
  2879. for p:=mem_min to lo_mem_max do was_free[p]:=free[p];
  2880. for p:=hi_mem_min to mem_end do was_free[p]:=free[p];
  2881.   {|was_free:=free| might be faster}
  2882. was_mem_end:=mem_end; was_lo_max:=lo_mem_max; was_hi_min:=hi_mem_min;
  2883. gubed
  2884. @ @<Check single-word...@>=
  2885. p:=avail; q:=null; clobbered:=false;
  2886. while p<>null do
  2887.   begin if (p>mem_end)or(p<hi_mem_min) then clobbered:=true
  2888.   else if free[p] then clobbered:=true;
  2889.   if clobbered then
  2890.     begin print_nl("AVAIL list clobbered at ");
  2891. @.AVAIL list clobbered...@>
  2892.     print_int(q); goto done1;
  2893.     end;
  2894.   free[p]:=true; q:=p; p:=link(q);
  2895.   end;
  2896. done1:
  2897. @ @<Check variable-size...@>=
  2898. p:=rover; q:=null; clobbered:=false;
  2899. repeat if (p>=lo_mem_max)or(p<mem_min) then clobbered:=true
  2900.   else if (rlink(p)>=lo_mem_max)or(rlink(p)<mem_min) then clobbered:=true
  2901.   else if  not(is_empty(p))or(node_size(p)<2)or@|
  2902.    (p+node_size(p)>lo_mem_max)or@| (llink(rlink(p))<>p) then clobbered:=true;
  2903.   if clobbered then
  2904.   begin print_nl("Double-AVAIL list clobbered at ");
  2905.   print_int(q); goto done2;
  2906.   end;
  2907. for q:=p to p+node_size(p)-1 do {mark all locations free}
  2908.   begin if free[q] then
  2909.     begin print_nl("Doubly free location at ");
  2910. @.Doubly free location...@>
  2911.     print_int(q); goto done2;
  2912.     end;
  2913.   free[q]:=true;
  2914.   end;
  2915. q:=p; p:=rlink(p);
  2916. until p=rover;
  2917. done2:
  2918. @ @<Check flags...@>=
  2919. p:=mem_min;
  2920. while p<=lo_mem_max do {node |p| should not be empty}
  2921.   begin if is_empty(p) then
  2922.     begin print_nl("Bad flag at "); print_int(p);
  2923. @.Bad flag...@>
  2924.     end;
  2925.   while (p<=lo_mem_max) and not free[p] do incr(p);
  2926.   while (p<=lo_mem_max) and free[p] do incr(p);
  2927.   end
  2928. @ @<Print newly busy...@>=
  2929. begin print_nl("New busy locs:");
  2930. for p:=mem_min to lo_mem_max do
  2931.   if not free[p] and ((p>was_lo_max) or was_free[p]) then
  2932.     begin print_char(" "); print_int(p);
  2933.     end;
  2934. for p:=hi_mem_min to mem_end do
  2935.   if not free[p] and
  2936.    ((p<was_hi_min) or (p>was_mem_end) or was_free[p]) then
  2937.     begin print_char(" "); print_int(p);
  2938.     end;
  2939. @ The |search_mem| procedure attempts to answer the question ``Who points
  2940. to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
  2941. that might not be of type |two_halves|. Strictly speaking, this is
  2942. @^dirty \PASCAL@>
  2943. undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
  2944. point to |p| purely by coincidence). But for debugging purposes, we want
  2945. to rule out the places that do {\sl not\/} point to |p|, so a few false
  2946. drops are tolerable.
  2947. @p @!debug procedure search_mem(@!p:pointer); {look for pointers to |p|}
  2948. var q:integer; {current position being searched}
  2949. begin for q:=mem_min to lo_mem_max do
  2950.   begin if link(q)=p then
  2951.     begin print_nl("LINK("); print_int(q); print_char(")");
  2952.     end;
  2953.   if info(q)=p then
  2954.     begin print_nl("INFO("); print_int(q); print_char(")");
  2955.     end;
  2956.   end;
  2957. for q:=hi_mem_min to mem_end do
  2958.   begin if link(q)=p then
  2959.     begin print_nl("LINK("); print_int(q); print_char(")");
  2960.     end;
  2961.   if info(q)=p then
  2962.     begin print_nl("INFO("); print_int(q); print_char(")");
  2963.     end;
  2964.   end;
  2965. @<Search |eqtb| for equivalents equal to |p|@>;
  2966. @<Search |save_stack| for equivalents that point to |p|@>;
  2967. @<Search |hyph_list| for pointers to |p|@>;
  2968. gubed
  2969. @* \[12] Displaying boxes.
  2970. We can reinforce our knowledge of the data structures just introduced
  2971. by considering two procedures that display a list in symbolic form.
  2972. The first of these, called |short_display|, is used in ``overfull box''
  2973. messages to give the top-level description of a list. The other one,
  2974. called |show_node_list|, prints a detailed description of exactly what
  2975. is in the data structure.
  2976. The philosophy of |short_display| is to ignore the fine points about exactly
  2977. what is inside boxes, except that ligatures and discretionary breaks are
  2978. expanded. As a result, |short_display| is a recursive procedure, but the
  2979. recursion is never more than one level deep.
  2980. @^recursion@>
  2981. A global variable |font_in_short_display| keeps track of the font code that
  2982. is assumed to be present when |short_display| begins; deviations from this
  2983. font will be printed.
  2984. @<Glob...@>=
  2985. @!font_in_short_display:integer; {an internal font number}
  2986. @ Boxes, rules, inserts, whatsits, marks, and things in general that are
  2987. sort of ``complicated'' are indicated only by printing `\.{[]}'.
  2988. @p procedure short_display(@!p:integer); {prints highlights of list |p|}
  2989. var n:integer; {for replacement counts}
  2990. begin while p>mem_min do
  2991.   begin if is_char_node(p) then
  2992.     begin if p<=mem_end then
  2993.       begin if font(p)<>font_in_short_display then
  2994.         begin if (font(p)<font_base)or(font(p)>font_max) then
  2995.           print_char("*")
  2996. @.*\relax@>
  2997.         else @<Print the font identifier for |font(p)|@>;
  2998.         print_char(" "); font_in_short_display:=font(p);
  2999.         end;
  3000.       print_ASCII(qo(character(p)));
  3001.       end;
  3002.     end
  3003.   else @<Print a short indication of the contents of node |p|@>;
  3004.   p:=link(p);
  3005.   end;
  3006. @ @<Print a short indication of the contents of node |p|@>=
  3007. case type(p) of
  3008. hlist_node,vlist_node,ins_node,whatsit_node,mark_node,adjust_node,
  3009.   unset_node: print("[]");
  3010. rule_node: print_char("|");
  3011. glue_node: if glue_ptr(p)<>zero_glue then print_char(" ");
  3012. math_node: print_char("$");
  3013. ligature_node: short_display(lig_ptr(p));
  3014. disc_node: begin short_display(pre_break(p));
  3015.   short_display(post_break(p));@/
  3016.   n:=replace_count(p);
  3017.   while n>0 do
  3018.     begin if link(p)<>null then p:=link(p);
  3019.     decr(n);
  3020.     end;
  3021.   end;
  3022. othercases do_nothing
  3023. endcases
  3024. @ The |show_node_list| routine requires some auxiliary subroutines: one to
  3025. print a font-and-character combination, one to print a token list without
  3026. its reference count, and one to print a rule dimension.
  3027. @p procedure print_font_and_char(@!p:integer); {prints |char_node| data}
  3028. begin if p>mem_end then print_esc("CLOBBERED.")
  3029. else  begin if (font(p)<font_base)or(font(p)>font_max) then print_char("*")
  3030. @.*\relax@>
  3031.   else @<Print the font identifier for |font(p)|@>;
  3032.   print_char(" "); print_ASCII(qo(character(p)));
  3033.   end;
  3034. procedure print_mark(@!p:integer); {prints token list data in braces}
  3035. begin print_char("{");
  3036. if (p<hi_mem_min)or(p>mem_end) then print_esc("CLOBBERED.")
  3037. else show_token_list(link(p),null,max_print_line-10);
  3038. print_char("}");
  3039. procedure print_rule_dimen(@!d:scaled); {prints dimension in rule node}
  3040. begin if is_running(d) then print_char("*") else print_scaled(d);
  3041. @.*\relax@>
  3042. @ Then there is a subroutine that prints glue stretch and shrink, possibly
  3043. followed by the name of finite units:
  3044. @p procedure print_glue(@!d:scaled;@!order:integer;@!s:str_number);
  3045.   {prints a glue component}
  3046. begin print_scaled(d);
  3047. if (order<normal)or(order>filll) then print("foul")
  3048. else if order>normal then
  3049.   begin print("fil");
  3050.   while order>fil do
  3051.     begin print_char("l"); decr(order);
  3052.     end;
  3053.   end
  3054. else if s<>0 then print(s);
  3055. @ The next subroutine prints a whole glue specification.
  3056. @p procedure print_spec(@!p:integer;@!s:str_number);
  3057.   {prints a glue specification}
  3058. begin if (p<mem_min)or(p>=lo_mem_max) then print_char("*")
  3059. @.*\relax@>
  3060. else  begin print_scaled(width(p));
  3061.   if s<>0 then print(s);
  3062.   if stretch(p)<>0 then
  3063.     begin print(" plus "); print_glue(stretch(p),stretch_order(p),s);
  3064.     end;
  3065.   if shrink(p)<>0 then
  3066.     begin print(" minus "); print_glue(shrink(p),shrink_order(p),s);
  3067.     end;
  3068.   end;
  3069. @ We also need to declare some procedures that appear later in this
  3070. documentation.
  3071. @p @<Declare procedures needed for displaying the elements of mlists@>@;
  3072. @<Declare the procedure called |print_skip_param|@>
  3073. @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
  3074. @^recursion@>
  3075. up to a given maximum number of levels.  The history of nesting is indicated
  3076. by the current string, which will be printed at the beginning of each line;
  3077. the length of this string, namely |cur_length|, is the depth of nesting.
  3078. Recursive calls on |show_node_list| therefore use the following pattern:
  3079. @d node_list_display(#)==
  3080.   begin append_char("."); show_node_list(#); flush_char;
  3081.   end {|str_room| need not be checked; see |show_box| below}
  3082. @ A global variable called |depth_threshold| is used to record the maximum
  3083. depth of nesting for which |show_node_list| will show information.  If we
  3084. have |depth_threshold=0|, for example, only the top level information will
  3085. be given and no sublists will be traversed. Another global variable, called
  3086. |breadth_max|, tells the maximum number of items to show at each level;
  3087. |breadth_max| had better be positive, or you won't see anything.
  3088. @<Glob...@>=
  3089. @!depth_threshold : integer; {maximum nesting depth in box displays}
  3090. @!breadth_max : integer; {maximum number of items shown at the same list level}
  3091. @ Now we are ready for |show_node_list| itself. This procedure has been
  3092. written to be ``extra robust'' in the sense that it should not crash or get
  3093. into a loop even if the data structures have been messed up by bugs in
  3094. the rest of the program. You can safely call its parent routine
  3095. |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
  3096. However, in the presence of bad data, the procedure may
  3097. @^dirty \PASCAL@>@^debugging@>
  3098. fetch a |memory_word| whose variant is different from the way it was stored;
  3099. for example, it might try to read |mem[p].hh| when |mem[p]|
  3100. contains a scaled integer, if |p| is a pointer that has been
  3101. clobbered or chosen at random.
  3102. @p procedure show_node_list(@!p:integer); {prints a node list symbolically}
  3103. label exit;
  3104. var n:integer; {the number of items already printed at this level}
  3105. @!g:real; {a glue ratio, as a floating point number}
  3106. begin if cur_length>depth_threshold then
  3107.   begin if p>null then print(" []");
  3108.     {indicate that there's been some truncation}
  3109.   return;
  3110.   end;
  3111. n:=0;
  3112. while p>mem_min do
  3113.   begin print_ln; print_current_string; {display the nesting history}
  3114.   if p>mem_end then {pointer out of range}
  3115.     begin print("Bad link, display aborted."); return;
  3116. @.Bad link...@>
  3117.     end;
  3118.   incr(n); if n>breadth_max then {time to stop}
  3119.     begin print("etc."); return;
  3120. @.etc@>
  3121.     end;
  3122.   @<Display node |p|@>;
  3123.   p:=link(p);
  3124.   end;
  3125. exit:
  3126. @ @<Display node |p|@>=
  3127. if is_char_node(p) then print_font_and_char(p)
  3128. else  case type(p) of
  3129.   hlist_node,vlist_node,unset_node: @<Display box |p|@>;
  3130.   rule_node: @<Display rule |p|@>;
  3131.   ins_node: @<Display insertion |p|@>;
  3132.   whatsit_node: @<Display the whatsit node |p|@>;
  3133.   glue_node: @<Display glue |p|@>;
  3134.   kern_node: @<Display kern |p|@>;
  3135.   math_node: @<Display math node |p|@>;
  3136.   ligature_node: @<Display ligature |p|@>;
  3137.   penalty_node: @<Display penalty |p|@>;
  3138.   disc_node: @<Display discretionary |p|@>;
  3139.   mark_node: @<Display mark |p|@>;
  3140.   adjust_node: @<Display adjustment |p|@>;
  3141.   @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
  3142.   othercases print("Unknown node type!")
  3143.   endcases
  3144. @ @<Display box |p|@>=
  3145. begin if type(p)=hlist_node then print_esc("h")
  3146. else if type(p)=vlist_node then print_esc("v")
  3147. else print_esc("unset");
  3148. print("box("); print_scaled(height(p)); print_char("+");
  3149. print_scaled(depth(p)); print(")x"); print_scaled(width(p));
  3150. if type(p)=unset_node then
  3151.   @<Display special fields of the unset node |p|@>
  3152. else  begin @<Display the value of |glue_set(p)|@>;
  3153.   if shift_amount(p)<>0 then
  3154.     begin print(", shifted "); print_scaled(shift_amount(p));
  3155.     end;
  3156.   end;
  3157. node_list_display(list_ptr(p)); {recursive call}
  3158. @ @<Display special fields of the unset node |p|@>=
  3159. begin if span_count(p)<>min_quarterword then
  3160.   begin print(" ("); print_int(qo(span_count(p))+1);
  3161.   print(" columns)");
  3162.   end;
  3163. if glue_stretch(p)<>0 then
  3164.   begin print(", stretch "); print_glue(glue_stretch(p),glue_order(p),0);
  3165.   end;
  3166. if glue_shrink(p)<>0 then
  3167.   begin print(", shrink "); print_glue(glue_shrink(p),glue_sign(p),0);
  3168.   end;
  3169. @ The code will have to change in this place if |glue_ratio| is
  3170. a structured type instead of an ordinary |real|. Note that this routine
  3171. should avoid arithmetic errors even if the |glue_set| field holds an
  3172. arbitrary random value. The following code assumes that a properly
  3173. formed nonzero |real| number has absolute value $2^{20}$ or more when
  3174. it is regarded as an integer; this precaution was adequate to prevent
  3175. floating point underflow on the author's computer.
  3176. @^system dependencies@>
  3177. @^dirty \PASCAL@>
  3178. @<Display the value of |glue_set(p)|@>=
  3179. g:=float(glue_set(p));
  3180. if (g<>float_constant(0))and(glue_sign(p)<>normal) then
  3181.   begin print(", glue set ");
  3182.   if glue_sign(p)=shrinking then print("- ");
  3183.   if abs(mem[p+glue_offset].int)<@'4000000 then print("?.?")
  3184.   else if abs(g)>float_constant(20000) then
  3185.     begin if g>float_constant(0) then print_char(">")
  3186.     else print("< -");
  3187.     print_glue(20000*unity,glue_order(p),0);
  3188.     end
  3189.   else print_glue(round(unity*g),glue_order(p),0);
  3190. @^real multiplication@>
  3191.   end
  3192. @ @<Display rule |p|@>=
  3193. begin print_esc("rule("); print_rule_dimen(height(p)); print_char("+");
  3194. print_rule_dimen(depth(p)); print(")x"); print_rule_dimen(width(p));
  3195. @ @<Display insertion |p|@>=
  3196. begin print_esc("insert"); print_int(qo(subtype(p)));
  3197. print(", natural size "); print_scaled(height(p));
  3198. print("; split("); print_spec(split_top_ptr(p),0);
  3199. print_char(","); print_scaled(depth(p));
  3200. print("); float cost "); print_int(float_cost(p));
  3201. node_list_display(ins_ptr(p)); {recursive call}
  3202. @ @<Display glue |p|@>=
  3203. if subtype(p)>=a_leaders then @<Display leaders |p|@>
  3204. else  begin print_esc("glue");
  3205.   if subtype(p)<>normal then
  3206.     begin print_char("(");
  3207.     if subtype(p)<cond_math_glue then
  3208.       print_skip_param(subtype(p)-1)
  3209.     else if subtype(p)=cond_math_glue then print_esc("nonscript")
  3210.     else print_esc("mskip");
  3211.     print_char(")");
  3212.     end;
  3213.   if subtype(p)<>cond_math_glue then
  3214.     begin print_char(" ");
  3215.     if subtype(p)<cond_math_glue then print_spec(glue_ptr(p),0)
  3216.     else print_spec(glue_ptr(p),"mu");
  3217.     end;
  3218.   end
  3219. @ @<Display leaders |p|@>=
  3220. begin print_esc("");
  3221. if subtype(p)=c_leaders then print_char("c")
  3222. else if subtype(p)=x_leaders then print_char("x");
  3223. print("leaders "); print_spec(glue_ptr(p),0);
  3224. node_list_display(leader_ptr(p)); {recursive call}
  3225. @ An ``explicit'' kern value is indicated implicitly by an explicit space.
  3226. @<Display kern |p|@>=
  3227. if subtype(p)<>mu_glue then
  3228.   begin print_esc("kern");
  3229.   if subtype(p)<>normal then print_char(" ");
  3230.   print_scaled(width(p));
  3231.   if subtype(p)=acc_kern then print(" (for accent)");
  3232. @.for accent@>
  3233.   end
  3234. else  begin print_esc("mkern"); print_scaled(width(p)); print("mu");
  3235.   end
  3236. @ @<Display math node |p|@>=
  3237. begin print_esc("math");
  3238. if subtype(p)=before then print("on")
  3239. else print("off");
  3240. if width(p)<>0 then
  3241.   begin print(", surrounded "); print_scaled(width(p));
  3242.   end;
  3243. @ @<Display ligature |p|@>=
  3244. begin print_font_and_char(lig_char(p)); print(" (ligature ");
  3245. if subtype(p)>1 then print_char("|");
  3246. font_in_short_display:=font(lig_char(p)); short_display(lig_ptr(p));
  3247. if odd(subtype(p)) then print_char("|");
  3248. print_char(")");
  3249. @ @<Display penalty |p|@>=
  3250. begin print_esc("penalty "); print_int(penalty(p));
  3251. @ The |post_break| list of a discretionary node is indicated by a prefixed
  3252. `\.{\char'174}' instead of the `\..' before the |pre_break| list.
  3253. @<Display discretionary |p|@>=
  3254. begin print_esc("discretionary");
  3255. if replace_count(p)>0 then
  3256.   begin print(" replacing "); print_int(replace_count(p));
  3257.   end;
  3258. node_list_display(pre_break(p)); {recursive call}
  3259. append_char("|"); show_node_list(post_break(p)); flush_char; {recursive call}
  3260. @ @<Display mark |p|@>=
  3261. begin print_esc("mark"); print_mark(mark_ptr(p));
  3262. @ @<Display adjustment |p|@>=
  3263. begin print_esc("vadjust"); node_list_display(adjust_ptr(p)); {recursive call}
  3264. @ The recursive machinery is started by calling |show_box|.
  3265. @^recursion@>
  3266. @p procedure show_box(@!p:pointer);
  3267. begin @<Assign the values |depth_threshold:=show_box_depth| and
  3268.   |breadth_max:=show_box_breadth|@>;
  3269. if breadth_max<=0 then breadth_max:=5;
  3270. if pool_ptr+depth_threshold>=pool_size then
  3271.   depth_threshold:=pool_size-pool_ptr-1;
  3272.   {now there's enough room for prefix string}
  3273. show_node_list(p); {the show starts at |p|}
  3274. print_ln;
  3275. @* \[13] Destroying boxes.
  3276. When we are done with a node list, we are obliged to return it to free
  3277. storage, including all of its sublists. The recursive procedure
  3278. |flush_node_list| does this for us.
  3279. @ First, however, we shall consider two non-recursive procedures that do
  3280. simpler tasks. The first of these, |delete_token_ref|, is called when
  3281. a pointer to a token list's reference count is being removed. This means
  3282. that the token list should disappear if the reference count was |null|,
  3283. otherwise the count should be decreased by one.
  3284. @^reference counts@>
  3285. @d token_ref_count(#) == info(#) {reference count preceding a token list}
  3286. @p procedure delete_token_ref(@!p:pointer); {|p| points to the reference count
  3287.   of a token list that is losing one reference}
  3288. begin if token_ref_count(p)=null then flush_list(p)
  3289. else decr(token_ref_count(p));
  3290. @ Similarly, |delete_glue_ref| is called when a pointer to a glue
  3291. specification is being withdrawn.
  3292. @^reference counts@>
  3293. @d fast_delete_glue_ref(#)==@t@>@;@/
  3294.   begin if glue_ref_count(#)=null then free_node(#,glue_spec_size)
  3295.   else decr(glue_ref_count(#));
  3296.   end
  3297. @p procedure delete_glue_ref(@!p:pointer); {|p| points to a glue specification}
  3298. fast_delete_glue_ref(p);
  3299. @ Now we are ready to delete any node list, recursively.
  3300. In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
  3301. and they are glue nodes in about half of the remaining cases.
  3302. @^recursion@>
  3303. @p procedure flush_node_list(@!p:pointer); {erase list of nodes starting at |p|}
  3304. label done; {go here when node |p| has been freed}
  3305. var q:pointer; {successor to node |p|}
  3306. begin while p<>null do
  3307. @^inner loop@>
  3308.   begin q:=link(p);
  3309.   if is_char_node(p) then free_avail(p)
  3310.   else  begin case type(p) of
  3311.     hlist_node,vlist_node,unset_node: begin flush_node_list(list_ptr(p));
  3312.       free_node(p,box_node_size); goto done;
  3313.       end;
  3314.     rule_node: begin free_node(p,rule_node_size); goto done;
  3315.       end;
  3316.     ins_node: begin flush_node_list(ins_ptr(p));
  3317.       delete_glue_ref(split_top_ptr(p));
  3318.       free_node(p,ins_node_size); goto done;
  3319.       end;
  3320.     whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>;
  3321.     glue_node: begin fast_delete_glue_ref(glue_ptr(p));
  3322.       if leader_ptr(p)<>null then flush_node_list(leader_ptr(p));
  3323.       end;
  3324.     kern_node,math_node,penalty_node: do_nothing;
  3325.     ligature_node: flush_node_list(lig_ptr(p));
  3326.     mark_node: delete_token_ref(mark_ptr(p));
  3327.     disc_node: begin flush_node_list(pre_break(p));
  3328.       flush_node_list(post_break(p));
  3329.       end;
  3330.     adjust_node: flush_node_list(adjust_ptr(p));
  3331.     @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
  3332.     othercases confusion("flushing")
  3333. @:this can't happen flushing}{\quad flushing@>
  3334.     endcases;@/
  3335.     free_node(p,small_node_size);
  3336.     done:end;
  3337.   p:=q;
  3338.   end;
  3339. @* \[14] Copying boxes.
  3340. Another recursive operation that acts on boxes is sometimes needed: The
  3341. procedure |copy_node_list| returns a pointer to another node list that has
  3342. the same structure and meaning as the original. Note that since glue
  3343. specifications and token lists have reference counts, we need not make
  3344. copies of them. Reference counts can never get too large to fit in a
  3345. halfword, since each pointer to a node is in a different memory address,
  3346. and the total number of memory addresses fits in a halfword.
  3347. @^recursion@>
  3348. @^reference counts@>
  3349. (Well, there actually are also references from outside |mem|; if the
  3350. |save_stack| is made arbitrarily large, it would theoretically be possible
  3351. to break \TeX\ by overflowing a reference count. But who would want to do that?)
  3352. @d add_token_ref(#)==incr(token_ref_count(#)) {new reference to a token list}
  3353. @d add_glue_ref(#)==incr(glue_ref_count(#)) {new reference to a glue spec}
  3354. @ The copying procedure copies words en masse without bothering
  3355. to look at their individual fields. If the node format changes---for
  3356. example, if the size is altered, or if some link field is moved to another
  3357. relative position---then this code may need to be changed too.
  3358. @^data structure assumptions@>
  3359. @p function copy_node_list(@!p:pointer):pointer; {makes a duplicate of the
  3360.   node list that starts at |p| and returns a pointer to the new list}
  3361. var h:pointer; {temporary head of copied list}
  3362. @!q:pointer; {previous position in new list}
  3363. @!r:pointer; {current node being fabricated for new list}
  3364. @!words:0..5; {number of words remaining to be copied}
  3365. begin h:=get_avail; q:=h;
  3366. while p<>null do
  3367.   begin @<Make a copy of node |p| in node |r|@>;
  3368.   link(q):=r; q:=r; p:=link(p);
  3369.   end;
  3370. link(q):=null; q:=link(h); free_avail(h);
  3371. copy_node_list:=q;
  3372. @ @<Make a copy of node |p|...@>=
  3373. words:=1; {this setting occurs in more branches than any other}
  3374. if is_char_node(p) then r:=get_avail
  3375. else @<Case statement to copy different types and set |words| to the number
  3376.   of initial words not yet copied@>;
  3377. while words>0 do
  3378.   begin decr(words); mem[r+words]:=mem[p+words];
  3379.   end
  3380. @ @<Case statement to copy...@>=
  3381. case type(p) of
  3382. hlist_node,vlist_node,unset_node: begin r:=get_node(box_node_size);
  3383.   mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
  3384.   list_ptr(r):=copy_node_list(list_ptr(p)); {this affects |mem[r+5]|}
  3385.   words:=5;
  3386.   end;
  3387. rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
  3388.   end;
  3389. ins_node: begin r:=get_node(ins_node_size); mem[r+4]:=mem[p+4];
  3390.   add_glue_ref(split_top_ptr(p));
  3391.   ins_ptr(r):=copy_node_list(ins_ptr(p)); {this affects |mem[r+4]|}
  3392.   words:=ins_node_size-1;
  3393.   end;
  3394. whatsit_node:@<Make a partial copy of the whatsit node |p| and make |r|
  3395.   point to it; set |words| to the number of initial words not yet copied@>;
  3396. glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
  3397.   glue_ptr(r):=glue_ptr(p); leader_ptr(r):=copy_node_list(leader_ptr(p));
  3398.   end;
  3399. kern_node,math_node,penalty_node: begin r:=get_node(small_node_size);
  3400.   words:=small_node_size;
  3401.   end;
  3402. ligature_node: begin r:=get_node(small_node_size);
  3403.   mem[lig_char(r)]:=mem[lig_char(p)]; {copy |font| and |character|}
  3404.   lig_ptr(r):=copy_node_list(lig_ptr(p));
  3405.   end;
  3406. disc_node: begin r:=get_node(small_node_size);
  3407.   pre_break(r):=copy_node_list(pre_break(p));
  3408.   post_break(r):=copy_node_list(post_break(p));
  3409.   end;
  3410. mark_node: begin r:=get_node(small_node_size); add_token_ref(mark_ptr(p));
  3411.   words:=small_node_size;
  3412.   end;
  3413. adjust_node: begin r:=get_node(small_node_size);
  3414.   adjust_ptr(r):=copy_node_list(adjust_ptr(p));
  3415.   end; {|words=1=small_node_size-1|}
  3416. othercases confusion("copying")
  3417. @:this can't happen copying}{\quad copying@>
  3418. endcases
  3419. @* \[15] The command codes.
  3420. Before we can go any further, we need to define symbolic names for the internal
  3421. code numbers that represent the various commands obeyed by \TeX. These codes
  3422. are somewhat arbitrary, but not completely so. For example, the command
  3423. codes for character types are fixed by the language, since a user says,
  3424. e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
  3425. and the command code |math_shift| is equal to~3. Some other codes have
  3426. been made adjacent so that |case| statements in the program need not consider
  3427. cases that are widely spaced, or so that |case| statements can be replaced
  3428. by |if| statements.
  3429. At any rate, here is the list, for future reference. First come the
  3430. ``catcode'' commands, several of which share their numeric codes with
  3431. ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
  3432. @d escape=0 {escape delimiter (called \.\\ in {\sl The \TeX book\/})}
  3433. @:TeXbook}{\sl The \TeX book@>
  3434. @d relax=0 {do nothing ( \.{\\relax} )}
  3435. @d left_brace=1 {beginning of a group ( \.\{ )}
  3436. @d right_brace=2 {ending of a group ( \.\} )}
  3437. @d math_shift=3 {mathematics shift character ( \.\$ )}
  3438. @d tab_mark=4 {alignment delimiter ( \.\&, \.{\\span} )}
  3439. @d car_ret=5 {end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )}
  3440. @d out_param=5 {output a macro parameter}
  3441. @d mac_param=6 {macro parameter symbol ( \.\# )}
  3442. @d sup_mark=7 {superscript ( \.{\char'136} )}
  3443. @d sub_mark=8 {subscript ( \.{\char'137} )}
  3444. @d ignore=9 {characters to ignore ( \.{\^\^J} )}
  3445. @d endv=9 {end of \<v_j> list in alignment template}
  3446. @d spacer=10 {characters equivalent to blank space ( \.{\ } )}
  3447. @d letter=11 {characters regarded as letters ( \.{A..Z}, \.{a..z} )}
  3448. @d other_char=12 {none of the special character types}
  3449. @d active_char=13 {characters that invoke macros ( \.{\^\^[} )}
  3450. @d par_end=13 {end of paragraph ( \.{\\par} )}
  3451. @d match=13 {match a macro parameter}
  3452. @d comment=14 {characters that introduce comments ( \.\% )}
  3453. @d end_match=14 {end of parameters to macro}
  3454. @d stop=14 {end of job ( \.{\\end}, \.{\\dump} )}
  3455. @d invalid_char=15 {characters that shouldn't appear ( \.{\^\^?} )}
  3456. @d delim_num=15 {specify delimiter numerically ( \.{\\delimiter} )}
  3457. @d max_char_code=15 {largest catcode for individual characters}
  3458. @ Next are the ordinary run-of-the-mill command codes.  Codes that are
  3459. |min_internal| or more represent internal quantities that might be
  3460. expanded by `\.{\\the}'.
  3461. @d char_num=16 {character specified numerically ( \.{\\char} )}
  3462. @d math_char_num=17 {explicit math code ( \.{\\mathchar} )}
  3463. @d mark=18 {mark definition ( \.{\\mark} )}
  3464. @d xray=19 {peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)}
  3465. @d make_box=20 {make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)}
  3466. @d hmove=21 {horizontal motion ( \.{\\moveleft}, \.{\\moveright} )}
  3467. @d vmove=22 {vertical motion ( \.{\\raise}, \.{\\lower} )}
  3468. @d un_hbox=23 {unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )}
  3469. @d un_vbox=24 {unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )}
  3470. @d remove_item=25 {nullify last item ( \.{\\unpenalty},
  3471.   \.{\\unkern}, \.{\\unskip} )}
  3472. @d hskip=26 {horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)}
  3473. @d vskip=27 {vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)}
  3474. @d mskip=28 {math glue ( \.{\\mskip} )}
  3475. @d kern=29 {fixed space ( \.{\\kern})}
  3476. @d mkern=30 {math kern ( \.{\\mkern} )}
  3477. @d leader_ship=31 {use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)}
  3478. @d halign=32 {horizontal table alignment ( \.{\\halign} )}
  3479. @d valign=33 {vertical table alignment ( \.{\\valign} )}
  3480. @d no_align=34 {temporary escape from alignment ( \.{\\noalign} )}
  3481. @d vrule=35 {vertical rule ( \.{\\vrule} )}
  3482. @d hrule=36 {horizontal rule ( \.{\\hrule} )}
  3483. @d insert=37 {vlist inserted in box ( \.{\\insert} )}
  3484. @d vadjust=38 {vlist inserted in enclosing paragraph ( \.{\\vadjust} )}
  3485. @d ignore_spaces=39 {gobble |spacer| tokens ( \.{\\ignorespaces} )}
  3486. @d after_assignment=40 {save till assignment is done ( \.{\\afterassignment} )}
  3487. @d after_group=41 {save till group is done ( \.{\\aftergroup} )}
  3488. @d break_penalty=42 {additional badness ( \.{\\penalty} )}
  3489. @d start_par=43 {begin paragraph ( \.{\\indent}, \.{\\noindent} )}
  3490. @d ital_corr=44 {italic correction ( \.{\\/} )}
  3491. @d accent=45 {attach accent in text ( \.{\\accent} )}
  3492. @d math_accent=46 {attach accent in math ( \.{\\mathaccent} )}
  3493. @d discretionary=47 {discretionary texts ( \.{\\-}, \.{\\discretionary} )}
  3494. @d eq_no=48 {equation number ( \.{\\eqno}, \.{\\leqno} )}
  3495. @d left_right=49 {variable delimiter ( \.{\\left}, \.{\\right} )}
  3496. @d math_comp=50 {component of formula ( \.{\\mathbin}, etc.~)}
  3497. @d limit_switch=51 {diddle limit conventions ( \.{\\displaylimits}, etc.~)}
  3498. @d above=52 {generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)}
  3499. @d math_style=53 {style specification ( \.{\\displaystyle}, etc.~)}
  3500. @d math_choice=54 {choice specification ( \.{\\mathchoice} )}
  3501. @d non_script=55 {conditional math glue ( \.{\\nonscript} )}
  3502. @d vcenter=56 {vertically center a vbox ( \.{\\vcenter} )}
  3503. @d case_shift=57 {force specific case ( \.{\\lowercase}, \.{\\uppercase}~)}
  3504. @d message=58 {send to user ( \.{\\message}, \.{\\errmessage} )}
  3505. @d extension=59 {extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)}
  3506. @d in_stream=60 {files for reading ( \.{\\openin}, \.{\\closein} )}
  3507. @d begin_group=61 {begin local grouping ( \.{\\begingroup} )}
  3508. @d end_group=62 {end local grouping ( \.{\\endgroup} )}
  3509. @d omit=63 {omit alignment template ( \.{\\omit} )}
  3510. @d ex_space=64 {explicit space ( \.{\\\ } )}
  3511. @d no_boundary=65 {suppress boundary ligatures ( \.{\\noboundary} )}
  3512. @d radical=66 {square root and similar signs ( \.{\\radical} )}
  3513. @d end_cs_name=67 {end control sequence ( \.{\\endcsname} )}
  3514. @d min_internal=68 {the smallest code that can follow \.{\\the}}
  3515. @d char_given=68 {character code defined by \.{\\chardef}}
  3516. @d math_given=69 {math code defined by \.{\\mathchardef}}
  3517. @d last_item=70 {most recent item ( \.{\\lastpenalty},
  3518.   \.{\\lastkern}, \.{\\lastskip} )}
  3519. @d max_non_prefixed_command=70 {largest command code that can't be \.{\\global}}
  3520. @ The next codes are special; they all relate to mode-independent
  3521. assignment of values to \TeX's internal registers or tables.
  3522. Codes that are |max_internal| or less represent internal quantities
  3523. that might be expanded by `\.{\\the}'.
  3524. @d toks_register=71 {token list register ( \.{\\toks} )}
  3525. @d assign_toks=72 {special token list ( \.{\\output}, \.{\\everypar}, etc.~)}
  3526. @d assign_int=73 {user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)}
  3527. @d assign_dimen=74 {user-defined length ( \.{\\hsize}, etc.~)}
  3528. @d assign_glue=75 {user-defined glue ( \.{\\baselineskip}, etc.~)}
  3529. @d assign_mu_glue=76 {user-defined muglue ( \.{\\thinmuskip}, etc.~)}
  3530. @d assign_font_dimen=77 {user-defined font dimension ( \.{\\fontdimen} )}
  3531. @d assign_font_int=78 {user-defined font integer ( \.{\\hyphenchar},
  3532.   \.{\\skewchar} )}
  3533. @d set_aux=79 {specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )}
  3534. @d set_prev_graf=80 {specify state info ( \.{\\prevgraf} )}
  3535. @d set_page_dimen=81 {specify state info ( \.{\\pagegoal}, etc.~)}
  3536. @d set_page_int=82 {specify state info ( \.{\\deadcycles},
  3537.   \.{\\insertpenalties} )}
  3538. @d set_box_dimen=83 {change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )}
  3539. @d set_shape=84 {specify fancy paragraph shape ( \.{\\parshape} )}
  3540. @d def_code=85 {define a character code ( \.{\\catcode}, etc.~)}
  3541. @d def_family=86 {declare math fonts ( \.{\\textfont}, etc.~)}
  3542. @d set_font=87 {set current font ( font identifiers )}
  3543. @d def_font=88 {define a font file ( \.{\\font} )}
  3544. @d register=89 {internal register ( \.{\\count}, \.{\\dimen}, etc.~)}
  3545. @d max_internal=89 {the largest code that can follow \.{\\the}}
  3546. @d advance=90 {advance a register or parameter ( \.{\\advance} )}
  3547. @d multiply=91 {multiply a register or parameter ( \.{\\multiply} )}
  3548. @d divide=92 {divide a register or parameter ( \.{\\divide} )}
  3549. @d prefix=93 {qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )}
  3550. @d let=94 {assign a command code ( \.{\\let}, \.{\\futurelet} )}
  3551. @d shorthand_def=95 {code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)}
  3552. @d read_to_cs=96 {read into a control sequence ( \.{\\read} )}
  3553. @d def=97 {macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )}
  3554. @d set_box=98 {set a box ( \.{\\setbox} )}
  3555. @d hyph_data=99 {hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )}
  3556. @d set_interaction=100 {define level of interaction ( \.{\\batchmode}, etc.~)}
  3557. @d max_command=100 {the largest command code seen at |big_switch|}
  3558. @ The remaining command codes are extra special, since they cannot get through
  3559. \TeX's scanner to the main control routine. They have been given values higher
  3560. than |max_command| so that their special nature is easily discernible.
  3561. The ``expandable'' commands come first.
  3562. @d undefined_cs=max_command+1 {initial state of most |eq_type| fields}
  3563. @d expand_after=max_command+2 {special expansion ( \.{\\expandafter} )}
  3564. @d no_expand=max_command+3 {special nonexpansion ( \.{\\noexpand} )}
  3565. @d input=max_command+4 {input a source file ( \.{\\input}, \.{\\endinput} )}
  3566. @d if_test=max_command+5 {conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)}
  3567. @d fi_or_else=max_command+6 {delimiters for conditionals ( \.{\\else}, etc.~)}
  3568. @d cs_name=max_command+7 {make a control sequence from tokens ( \.{\\csname} )}
  3569. @d convert=max_command+8 {convert to text ( \.{\\number}, \.{\\string}, etc.~)}
  3570. @d the=max_command+9 {expand an internal quantity ( \.{\\the} )}
  3571. @d top_bot_mark=max_command+10 {inserted mark ( \.{\\topmark}, etc.~)}
  3572. @d call=max_command+11 {non-long, non-outer control sequence}
  3573. @d long_call=max_command+12 {long, non-outer control sequence}
  3574. @d outer_call=max_command+13 {non-long, outer control sequence}
  3575. @d long_outer_call=max_command+14 {long, outer control sequence}
  3576. @d end_template=max_command+15 {end of an alignment template}
  3577. @d dont_expand=max_command+16 {the following token was marked by \.{\\noexpand}}
  3578. @d glue_ref=max_command+17 {the equivalent points to a glue specification}
  3579. @d shape_ref=max_command+18 {the equivalent points to a parshape specification}
  3580. @d box_ref=max_command+19 {the equivalent points to a box node, or is |null|}
  3581. @d data=max_command+20 {the equivalent is simply a halfword number}
  3582. @* \[16] The semantic nest.
  3583. \TeX\ is typically in the midst of building many lists at once. For example,
  3584. when a math formula is being processed, \TeX\ is in math mode and
  3585. working on an mlist; this formula has temporarily interrupted \TeX\ from
  3586. being in horizontal mode and building the hlist of a paragraph; and this
  3587. paragraph has temporarily interrupted \TeX\ from being in vertical mode
  3588. and building the vlist for the next page of a document. Similarly, when a
  3589. \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
  3590. interrupted from working in restricted horizontal mode, and it enters
  3591. internal vertical mode.  The ``semantic nest'' is a stack that
  3592. keeps track of what lists and modes are currently suspended.
  3593. At each level of processing we are in one of six modes:
  3594. \yskip\hang|vmode| stands for vertical mode (the page builder);
  3595. \hang|hmode| stands for horizontal mode (the paragraph builder);
  3596. \hang|mmode| stands for displayed formula mode;
  3597. \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
  3598. \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
  3599. \hang|-mmode| stands for math formula mode (not displayed).
  3600. \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
  3601. texts in the |ship_out| routine.
  3602. Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
  3603. \TeX's ``big semantic switch'' can select the appropriate thing to
  3604. do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
  3605. mode and |cur_cmd| is the current command code.
  3606. @d vmode=1 {vertical mode}
  3607. @d hmode=vmode+max_command+1 {horizontal mode}
  3608. @d mmode=hmode+max_command+1 {math mode}
  3609. @p procedure print_mode(@!m:integer); {prints the mode represented by |m|}
  3610. begin if m>0 then
  3611.   case m div (max_command+1) of
  3612.   0:print("vertical");
  3613.   1:print("horizontal");
  3614.   2:print("display math");
  3615.   end
  3616. else if m=0 then print("no")
  3617. else  case (-m) div (max_command+1) of
  3618.   0:print("internal vertical");
  3619.   1:print("restricted horizontal");
  3620.   2:print("math");
  3621.   end;
  3622. print(" mode");
  3623. @ The state of affairs at any semantic level can be represented by
  3624. five values:
  3625. \yskip\hang|mode| is the number representing the semantic mode, as
  3626. just explained.
  3627. \yskip\hang|head| is a |pointer| to a list head for the list being built;
  3628. |link(head)| therefore points to the first element of the list, or
  3629. to |null| if the list is empty.
  3630. \yskip\hang|tail| is a |pointer| to the final node of the list being
  3631. built; thus, |tail=head| if and only if the list is empty.
  3632. \yskip\hang|prev_graf| is the number of lines of the current paragraph that
  3633. have already been put into the present vertical list.
  3634. \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
  3635. that is needed to characterize the situation.
  3636. \yskip\noindent
  3637. In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
  3638. value representing the depth of the previous box, for use in baseline
  3639. calculations, or it is |<=-1000|pt if the next box on the vertical list is to
  3640. be exempt from baseline calculations.  In horizontal mode, |aux| is also
  3641. known as |space_factor| and |clang|; it holds the current space factor used in
  3642. spacing calculations, and the current language used for hyphenation.
  3643. (The value of |clang| is undefined in restricted horizontal mode.)
  3644. In math mode, |aux| is also known as |incompleat_noad|; if
  3645. not |null|, it points to a record that represents the numerator of a
  3646. generalized fraction for which the denominator is currently being formed
  3647. in the current list.
  3648. There is also a sixth quantity, |mode_line|, which correlates
  3649. the semantic nest with the user's input; |mode_line| contains the source
  3650. line number at which the current level of nesting was entered. The negative
  3651. of this line number is the |mode_line| at the level of the
  3652. user's output routine.
  3653. In horizontal mode, the |prev_graf| field is used for initial language data.
  3654. The semantic nest is an array called |nest| that holds the |mode|, |head|,
  3655. |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
  3656. below the currently active one. Information about the currently active
  3657. level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
  3658. |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
  3659. be pushed onto |nest| if necessary.
  3660. @d ignore_depth==-65536000 {|prev_depth| value that is ignored}
  3661. @<Types...@>=
  3662. @!list_state_record=record@!mode_field:-mmode..mmode;@+
  3663.   @!head_field,@!tail_field: pointer;
  3664.   @!pg_field,@!ml_field: integer;@+
  3665.   @!aux_field: memory_word;
  3666.   end;
  3667. @ @d mode==cur_list.mode_field {current mode}
  3668. @d head==cur_list.head_field {header node of current list}
  3669. @d tail==cur_list.tail_field {final node on current list}
  3670. @d prev_graf==cur_list.pg_field {number of paragraph lines accumulated}
  3671. @d aux==cur_list.aux_field {auxiliary data about the current list}
  3672. @d prev_depth==aux.sc {the name of |aux| in vertical mode}
  3673. @d space_factor==aux.hh.lh {part of |aux| in horizontal mode}
  3674. @d clang==aux.hh.rh {the other part of |aux| in horizontal mode}
  3675. @d incompleat_noad==aux.int {the name of |aux| in math mode}
  3676. @d mode_line==cur_list.ml_field {source file line number at beginning of list}
  3677. @<Glob...@>=
  3678. @!nest:array[0..nest_size] of list_state_record;
  3679. @!nest_ptr:0..nest_size; {first unused location of |nest|}
  3680. @!max_nest_stack:0..nest_size; {maximum of |nest_ptr| when pushing}
  3681. @!cur_list:list_state_record; {the ``top'' semantic state}
  3682. @!shown_mode:-mmode..mmode; {most recent mode shown by \.{\\tracingcommands}}
  3683. @ Here is a common way to make the current list grow:
  3684. @d tail_append(#)==begin link(tail):=#; tail:=link(tail);
  3685.   end
  3686. @ We will see later that the vertical list at the bottom semantic level is split
  3687. into two parts; the ``current page'' runs from |page_head| to |page_tail|,
  3688. and the ``contribution list'' runs from |contrib_head| to |tail| of
  3689. semantic level zero. The idea is that contributions are first formed in
  3690. vertical mode, then ``contributed'' to the current page (during which time
  3691. the page-breaking decisions are made). For now, we don't need to know
  3692. any more details about the page-building process.
  3693. @<Set init...@>=
  3694. nest_ptr:=0; max_nest_stack:=0;
  3695. mode:=vmode; head:=contrib_head; tail:=contrib_head;
  3696. prev_depth:=ignore_depth; mode_line:=0;
  3697. prev_graf:=0; shown_mode:=0;
  3698. @<Start a new current page@>;
  3699. @ When \TeX's work on one level is interrupted, the state is saved by
  3700. calling |push_nest|. This routine changes |head| and |tail| so that
  3701. a new (empty) list is begun; it does not change |mode| or |aux|.
  3702. @p procedure push_nest; {enter a new semantic level, save the old}
  3703. begin if nest_ptr>max_nest_stack then
  3704.   begin max_nest_stack:=nest_ptr;
  3705.   if nest_ptr=nest_size then overflow("semantic nest size",nest_size);
  3706. @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
  3707.   end;
  3708. nest[nest_ptr]:=cur_list; {stack the record}
  3709. incr(nest_ptr); head:=get_avail; tail:=head; prev_graf:=0; mode_line:=line;
  3710. @ Conversely, when \TeX\ is finished on the current level, the former
  3711. state is restored by calling |pop_nest|. This routine will never be
  3712. called at the lowest semantic level, nor will it be called unless |head|
  3713. is a node that should be returned to free memory.
  3714. @p procedure pop_nest; {leave a semantic level, re-enter the old}
  3715. begin free_avail(head); decr(nest_ptr); cur_list:=nest[nest_ptr];
  3716. @ Here is a procedure that displays what \TeX\ is working on, at all levels.
  3717. @p procedure@?print_totals; forward;@t\2@>
  3718. procedure show_activities;
  3719. var p:0..nest_size; {index into |nest|}
  3720. @!m:-mmode..mmode; {mode}
  3721. @!a:memory_word; {auxiliary}
  3722. @!q,@!r:pointer; {for showing the current page}
  3723. @!t:integer; {ditto}
  3724. begin nest[nest_ptr]:=cur_list; {put the top level into the array}
  3725. print_nl(""); print_ln;
  3726. for p:=nest_ptr downto 0 do
  3727.   begin m:=nest[p].mode_field; a:=nest[p].aux_field;
  3728.   print_nl("### "); print_mode(m);
  3729.   print(" entered at line "); print_int(abs(nest[p].ml_field));
  3730.   if m=hmode then if nest[p].pg_field <> @'40600000 then
  3731.     begin print(" (language"); print_int(nest[p].pg_field mod @'200000);
  3732.     print(":hyphenmin"); print_int(nest[p].pg_field div @'20000000);
  3733.     print_char(","); print_int((nest[p].pg_field div @'200000) mod @'100);
  3734.     print_char(")");
  3735.     end;
  3736.   if nest[p].ml_field<0 then print(" (\output routine)");
  3737.   if p=0 then
  3738.     begin @<Show the status of the current page@>;
  3739.     if link(contrib_head)<>null then
  3740.       print_nl("### recent contributions:");
  3741.     end;
  3742.   show_box(link(nest[p].head_field));
  3743.   @<Show the auxiliary field, |a|@>;
  3744.   end;
  3745. @ @<Show the auxiliary...@>=
  3746. case abs(m) div (max_command+1) of
  3747. 0: begin print_nl("prevdepth ");
  3748.   if a.sc<=ignore_depth then print("ignored")
  3749.   else print_scaled(a.sc);
  3750.   if nest[p].pg_field<>0 then
  3751.     begin print(", prevgraf ");
  3752.     print_int(nest[p].pg_field); print(" line");
  3753.     if nest[p].pg_field<>1 then print_char("s");
  3754.     end;
  3755.   end;
  3756. 1: begin print_nl("spacefactor "); print_int(a.hh.lh);
  3757.   if m>0 then@+ if a.hh.rh>0 then
  3758.     begin print(", current language "); print_int(a.hh.rh);@+
  3759.     end;
  3760.   end;
  3761. 2: if a.int<>null then
  3762.   begin print("this will be denominator of:"); show_box(a.int);@+
  3763.   end;
  3764. end {there are no other cases}
  3765. @* \[17] The table of equivalents.
  3766. Now that we have studied the data structures for \TeX's semantic routines,
  3767. we ought to consider the data structures used by its syntactic routines. In
  3768. other words, our next concern will be
  3769. the tables that \TeX\ looks at when it is scanning
  3770. what the user has written.
  3771. The biggest and most important such table is called |eqtb|. It holds the
  3772. current ``equivalents'' of things; i.e., it explains what things mean
  3773. or what their current values are, for all quantities that are subject to
  3774. the nesting structure provided by \TeX's grouping mechanism. There are six
  3775. parts to |eqtb|:
  3776. \yskip\hang 1) |eqtb[active_base..(hash_base-1)]| holds the current
  3777. equivalents of single-character control sequences.
  3778. \yskip\hang 2) |eqtb[hash_base..(glue_base-1)]| holds the current
  3779. equivalents of multiletter control sequences.
  3780. \yskip\hang 3) |eqtb[glue_base..(local_base-1)]| holds the current
  3781. equivalents of glue parameters like the current baselineskip.
  3782. \yskip\hang 4) |eqtb[local_base..(int_base-1)]| holds the current
  3783. equivalents of local halfword quantities like the current box registers,
  3784. the current ``catcodes,'' the current font, and a pointer to the current
  3785. paragraph shape.
  3786. \yskip\hang 5) |eqtb[int_base..(dimen_base-1)]| holds the current
  3787. equivalents of fullword integer parameters like the current hyphenation
  3788. penalty.
  3789. \yskip\hang 6) |eqtb[dimen_base..eqtb_size]| holds the current equivalents
  3790. of fullword dimension parameters like the current hsize or amount of
  3791. hanging indentation.
  3792. \yskip\noindent Note that, for example, the current amount of
  3793. baselineskip glue is determined by the setting of a particular location
  3794. in region~3 of |eqtb|, while the current meaning of the control sequence
  3795. `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
  3796. \.{\\let}) appears in region~2.
  3797. @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
  3798. |two_halves|, and subdivided into three fields:
  3799. \yskip\hang 1) The |eq_level| (a quarterword) is the level of grouping at
  3800. which this equivalent was defined. If the level is |level_zero|, the
  3801. equivalent has never been defined; |level_one| refers to the outer level
  3802. (outside of all groups), and this level is also used for global
  3803. definitions that never go away. Higher levels are for equivalents that
  3804. will disappear at the end of their group.  @^global definitions@>
  3805. \yskip\hang 2) The |eq_type| (another quarterword) specifies what kind of
  3806. entry this is. There are many types, since each \TeX\ primitive like
  3807. \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
  3808. command codes above includes all possible settings of the |eq_type| field.
  3809. \yskip\hang 3) The |equiv| (a halfword) is the current equivalent value.
  3810. This may be a font number, a pointer into |mem|, or a variety of other
  3811. things.
  3812. @d eq_level_field(#)==#.hh.b1
  3813. @d eq_type_field(#)==#.hh.b0
  3814. @d equiv_field(#)==#.hh.rh
  3815. @d eq_level(#)==eq_level_field(eqtb[#]) {level of definition}
  3816. @d eq_type(#)==eq_type_field(eqtb[#]) {command code for equivalent}
  3817. @d equiv(#)==equiv_field(eqtb[#]) {equivalent value}
  3818. @d level_zero=min_quarterword {level for undefined quantities}
  3819. @d level_one=level_zero+1 {outermost level for defined quantities}
  3820. @ Many locations in |eqtb| have symbolic names. The purpose of the next
  3821. paragraphs is to define these names, and to set up the initial values of the
  3822. equivalents.
  3823. In the first region we have 256 equivalents for ``active characters'' that
  3824. act as control sequences, followed by 256 equivalents for single-character
  3825. control sequences.
  3826. Then comes region~2, which corresponds to the hash table that we will
  3827. define later.  The maximum address in this region is used for a dummy
  3828. control sequence that is perpetually undefined. There also are several
  3829. locations for control sequences that are perpetually defined
  3830. (since they are used in error recovery).
  3831. @d active_base=1 {beginning of region 1, for active character equivalents}
  3832. @d single_base=active_base+256 {equivalents of one-character control sequences}
  3833. @d null_cs=single_base+256 {equivalent of \.{\\csname\\endcsname}}
  3834. @d hash_base=null_cs+1 {beginning of region 2, for the hash table}
  3835. @d frozen_control_sequence=hash_base+hash_size {for error recovery}
  3836. @d frozen_protection=frozen_control_sequence {inaccessible but definable}
  3837. @d frozen_cr=frozen_control_sequence+1 {permanent `\.{\\cr}'}
  3838. @d frozen_end_group=frozen_control_sequence+2 {permanent `\.{\\endgroup}'}
  3839. @d frozen_right=frozen_control_sequence+3 {permanent `\.{\\right}'}
  3840. @d frozen_fi=frozen_control_sequence+4 {permanent `\.{\\fi}'}
  3841. @d frozen_end_template=frozen_control_sequence+5 {permanent `\.{\\endtemplate}'}
  3842. @d frozen_endv=frozen_control_sequence+6 {second permanent `\.{\\endtemplate}'}
  3843. @d frozen_relax=frozen_control_sequence+7 {permanent `\.{\\relax}'}
  3844. @d end_write=frozen_control_sequence+8 {permanent `\.{\\endwrite}'}
  3845. @d frozen_dont_expand=frozen_control_sequence+9
  3846.   {permanent `\.{\\notexpanded:}'}
  3847. @d frozen_null_font=frozen_control_sequence+10
  3848.   {permanent `\.{\\nullfont}'}
  3849. @d font_id_base=frozen_null_font-font_base
  3850.   {begins table of 257 permanent font identifiers}
  3851. @d undefined_control_sequence=frozen_null_font+257 {dummy location}
  3852. @d glue_base=undefined_control_sequence+1 {beginning of region 3}
  3853. @<Initialize table entries...@>=
  3854. eq_type(undefined_control_sequence):=undefined_cs;
  3855. equiv(undefined_control_sequence):=null;
  3856. eq_level(undefined_control_sequence):=level_zero;
  3857. for k:=active_base to undefined_control_sequence-1 do
  3858.   eqtb[k]:=eqtb[undefined_control_sequence];
  3859. @ Here is a routine that displays the current meaning of an |eqtb| entry
  3860. in region 1 or~2. (Similar routines for the other regions will appear
  3861. below.)
  3862. @<Show equivalent |n|, in region 1 or 2@>=
  3863. begin sprint_cs(n); print_char("="); print_cmd_chr(eq_type(n),equiv(n));
  3864. if eq_type(n)>=call then
  3865.   begin print_char(":"); show_token_list(link(equiv(n)),null,32);
  3866.   end;
  3867. @ Region 3 of |eqtb| contains the 256 \.{\\skip} registers, as well as the
  3868. glue parameters defined here. It is important that the ``muskip''
  3869. parameters have larger numbers than the others.
  3870. @d line_skip_code=0 {interline glue if |baseline_skip| is infeasible}
  3871. @d baseline_skip_code=1 {desired glue between baselines}
  3872. @d par_skip_code=2 {extra glue just above a paragraph}
  3873. @d above_display_skip_code=3 {extra glue just above displayed math}
  3874. @d below_display_skip_code=4 {extra glue just below displayed math}
  3875. @d above_display_short_skip_code=5
  3876.   {glue above displayed math following short lines}
  3877. @d below_display_short_skip_code=6
  3878.   {glue below displayed math following short lines}
  3879. @d left_skip_code=7 {glue at left of justified lines}
  3880. @d right_skip_code=8 {glue at right of justified lines}
  3881. @d top_skip_code=9 {glue at top of main pages}
  3882. @d split_top_skip_code=10 {glue at top of split pages}
  3883. @d tab_skip_code=11 {glue between aligned entries}
  3884. @d space_skip_code=12 {glue between words (if not |zero_glue|)}
  3885. @d xspace_skip_code=13 {glue after sentences (if not |zero_glue|)}
  3886. @d par_fill_skip_code=14 {glue on last line of paragraph}
  3887. @d thin_mu_skip_code=15 {thin space in math formula}
  3888. @d med_mu_skip_code=16 {medium space in math formula}
  3889. @d thick_mu_skip_code=17 {thick space in math formula}
  3890. @d glue_pars=18 {total number of glue parameters}
  3891. @d skip_base=glue_base+glue_pars {table of 256 ``skip'' registers}
  3892. @d mu_skip_base=skip_base+256 {table of 256 ``muskip'' registers}
  3893. @d local_base=mu_skip_base+256 {beginning of region 4}
  3894. @d skip(#)==equiv(skip_base+#) {|mem| location of glue specification}
  3895. @d mu_skip(#)==equiv(mu_skip_base+#) {|mem| location of math glue spec}
  3896. @d glue_par(#)==equiv(glue_base+#) {|mem| location of glue specification}
  3897. @d line_skip==glue_par(line_skip_code)
  3898. @d baseline_skip==glue_par(baseline_skip_code)
  3899. @d par_skip==glue_par(par_skip_code)
  3900. @d above_display_skip==glue_par(above_display_skip_code)
  3901. @d below_display_skip==glue_par(below_display_skip_code)
  3902. @d above_display_short_skip==glue_par(above_display_short_skip_code)
  3903. @d below_display_short_skip==glue_par(below_display_short_skip_code)
  3904. @d left_skip==glue_par(left_skip_code)
  3905. @d right_skip==glue_par(right_skip_code)
  3906. @d top_skip==glue_par(top_skip_code)
  3907. @d split_top_skip==glue_par(split_top_skip_code)
  3908. @d tab_skip==glue_par(tab_skip_code)
  3909. @d space_skip==glue_par(space_skip_code)
  3910. @d xspace_skip==glue_par(xspace_skip_code)
  3911. @d par_fill_skip==glue_par(par_fill_skip_code)
  3912. @d thin_mu_skip==glue_par(thin_mu_skip_code)
  3913. @d med_mu_skip==glue_par(med_mu_skip_code)
  3914. @d thick_mu_skip==glue_par(thick_mu_skip_code)
  3915. @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
  3916. @ Sometimes we need to convert \TeX's internal code numbers into symbolic
  3917. form. The |print_skip_param| routine gives the symbolic name of a glue
  3918. parameter.
  3919. @<Declare the procedure called |print_skip_param|@>=
  3920. procedure print_skip_param(@!n:integer);
  3921. begin case n of
  3922. line_skip_code: print_esc("lineskip");
  3923. baseline_skip_code: print_esc("baselineskip");
  3924. par_skip_code: print_esc("parskip");
  3925. above_display_skip_code: print_esc("abovedisplayskip");
  3926. below_display_skip_code: print_esc("belowdisplayskip");
  3927. above_display_short_skip_code: print_esc("abovedisplayshortskip");
  3928. below_display_short_skip_code: print_esc("belowdisplayshortskip");
  3929. left_skip_code: print_esc("leftskip");
  3930. right_skip_code: print_esc("rightskip");
  3931. top_skip_code: print_esc("topskip");
  3932. split_top_skip_code: print_esc("splittopskip");
  3933. tab_skip_code: print_esc("tabskip");
  3934. space_skip_code: print_esc("spaceskip");
  3935. xspace_skip_code: print_esc("xspaceskip");
  3936. par_fill_skip_code: print_esc("parfillskip");
  3937. thin_mu_skip_code: print_esc("thinmuskip");
  3938. med_mu_skip_code: print_esc("medmuskip");
  3939. thick_mu_skip_code: print_esc("thickmuskip");
  3940. othercases print("[unknown glue parameter!]")
  3941. endcases;
  3942. @ The symbolic names for glue parameters are put into \TeX's hash table
  3943. by using the routine called |primitive|, defined below. Let us enter them
  3944. now, so that we don't have to list all those parameter names anywhere else.
  3945. @<Put each of \TeX's primitives into the hash table@>=
  3946. primitive("lineskip",assign_glue,glue_base+line_skip_code);@/
  3947. @!@:line_skip_}{\.{\\lineskip} primitive@>
  3948. primitive("baselineskip",assign_glue,glue_base+baseline_skip_code);@/
  3949. @!@:baseline_skip_}{\.{\\baselineskip} primitive@>
  3950. primitive("parskip",assign_glue,glue_base+par_skip_code);@/
  3951. @!@:par_skip_}{\.{\\parskip} primitive@>
  3952. primitive("abovedisplayskip",assign_glue,glue_base+above_display_skip_code);@/
  3953. @!@:above_display_skip_}{\.{\\abovedisplayskip} primitive@>
  3954. primitive("belowdisplayskip",assign_glue,glue_base+below_display_skip_code);@/
  3955. @!@:below_display_skip_}{\.{\\belowdisplayskip} primitive@>
  3956. primitive("abovedisplayshortskip",
  3957.   assign_glue,glue_base+above_display_short_skip_code);@/
  3958. @!@:above_display_short_skip_}{\.{\\abovedisplayshortskip} primitive@>
  3959. primitive("belowdisplayshortskip",
  3960.   assign_glue,glue_base+below_display_short_skip_code);@/
  3961. @!@:below_display_short_skip_}{\.{\\belowdisplayshortskip} primitive@>
  3962. primitive("leftskip",assign_glue,glue_base+left_skip_code);@/
  3963. @!@:left_skip_}{\.{\\leftskip} primitive@>
  3964. primitive("rightskip",assign_glue,glue_base+right_skip_code);@/
  3965. @!@:right_skip_}{\.{\\rightskip} primitive@>
  3966. primitive("topskip",assign_glue,glue_base+top_skip_code);@/
  3967. @!@:top_skip_}{\.{\\topskip} primitive@>
  3968. primitive("splittopskip",assign_glue,glue_base+split_top_skip_code);@/
  3969. @!@:split_top_skip_}{\.{\\splittopskip} primitive@>
  3970. primitive("tabskip",assign_glue,glue_base+tab_skip_code);@/
  3971. @!@:tab_skip_}{\.{\\tabskip} primitive@>
  3972. primitive("spaceskip",assign_glue,glue_base+space_skip_code);@/
  3973. @!@:space_skip_}{\.{\\spaceskip} primitive@>
  3974. primitive("xspaceskip",assign_glue,glue_base+xspace_skip_code);@/
  3975. @!@:xspace_skip_}{\.{\\xspaceskip} primitive@>
  3976. primitive("parfillskip",assign_glue,glue_base+par_fill_skip_code);@/
  3977. @!@:par_fill_skip_}{\.{\\parfillskip} primitive@>
  3978. primitive("thinmuskip",assign_mu_glue,glue_base+thin_mu_skip_code);@/
  3979. @!@:thin_mu_skip_}{\.{\\thinmuskip} primitive@>
  3980. primitive("medmuskip",assign_mu_glue,glue_base+med_mu_skip_code);@/
  3981. @!@:med_mu_skip_}{\.{\\medmuskip} primitive@>
  3982. primitive("thickmuskip",assign_mu_glue,glue_base+thick_mu_skip_code);@/
  3983. @!@:thick_mu_skip_}{\.{\\thickmuskip} primitive@>
  3984. @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
  3985. assign_glue,assign_mu_glue: if chr_code<skip_base then
  3986.     print_skip_param(chr_code-glue_base)
  3987.   else if chr_code<mu_skip_base then
  3988.     begin print_esc("skip"); print_int(chr_code-skip_base);
  3989.     end
  3990.   else  begin print_esc("muskip"); print_int(chr_code-mu_skip_base);
  3991.     end;
  3992. @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
  3993. @<Initialize table entries...@>=
  3994. equiv(glue_base):=zero_glue; eq_level(glue_base):=level_one;
  3995. eq_type(glue_base):=glue_ref;
  3996. for k:=glue_base+1 to local_base-1 do eqtb[k]:=eqtb[glue_base];
  3997. glue_ref_count(zero_glue):=glue_ref_count(zero_glue)+local_base-glue_base;
  3998. @ @<Show equivalent |n|, in region 3@>=
  3999. if n<skip_base then
  4000.   begin print_skip_param(n-glue_base); print_char("=");
  4001.   if n<glue_base+thin_mu_skip_code then print_spec(equiv(n),"pt")
  4002.   else print_spec(equiv(n),"mu");
  4003.   end
  4004. else if n<mu_skip_base then
  4005.   begin print_esc("skip"); print_int(n-skip_base); print_char("=");
  4006.   print_spec(equiv(n),"pt");
  4007.   end
  4008. else  begin print_esc("muskip"); print_int(n-mu_skip_base); print_char("=");
  4009.   print_spec(equiv(n),"mu");
  4010.   end
  4011. @ Region 4 of |eqtb| contains the local quantities defined here. The
  4012. bulk of this region is taken up by five tables that are indexed by eight-bit
  4013. characters; these tables are important to both the syntactic and semantic
  4014. portions of \TeX. There are also a bunch of special things like font and
  4015. token parameters, as well as the tables of \.{\\toks} and \.{\\box}
  4016. registers.
  4017. @d par_shape_loc=local_base {specifies paragraph shape}
  4018. @d output_routine_loc=local_base+1 {points to token list for \.{\\output}}
  4019. @d every_par_loc=local_base+2 {points to token list for \.{\\everypar}}
  4020. @d every_math_loc=local_base+3 {points to token list for \.{\\everymath}}
  4021. @d every_display_loc=local_base+4 {points to token list for \.{\\everydisplay}}
  4022. @d every_hbox_loc=local_base+5 {points to token list for \.{\\everyhbox}}
  4023. @d every_vbox_loc=local_base+6 {points to token list for \.{\\everyvbox}}
  4024. @d every_job_loc=local_base+7 {points to token list for \.{\\everyjob}}
  4025. @d every_cr_loc=local_base+8 {points to token list for \.{\\everycr}}
  4026. @d err_help_loc=local_base+9 {points to token list for \.{\\errhelp}}
  4027. @d toks_base=local_base+10 {table of 256 token list registers}
  4028. @d box_base=toks_base+256 {table of 256 box registers}
  4029. @d cur_font_loc=box_base+256 {internal font number outside math mode}
  4030. @d math_font_base=cur_font_loc+1 {table of 48 math font numbers}
  4031. @d cat_code_base=math_font_base+48
  4032.   {table of 256 command codes (the ``catcodes'')}
  4033. @d lc_code_base=cat_code_base+256 {table of 256 lowercase mappings}
  4034. @d uc_code_base=lc_code_base+256 {table of 256 uppercase mappings}
  4035. @d sf_code_base=uc_code_base+256 {table of 256 spacefactor mappings}
  4036. @d math_code_base=sf_code_base+256 {table of 256 math mode mappings}
  4037. @d int_base=math_code_base+256 {beginning of region 5}
  4038. @d par_shape_ptr==equiv(par_shape_loc)
  4039. @d output_routine==equiv(output_routine_loc)
  4040. @d every_par==equiv(every_par_loc)
  4041. @d every_math==equiv(every_math_loc)
  4042. @d every_display==equiv(every_display_loc)
  4043. @d every_hbox==equiv(every_hbox_loc)
  4044. @d every_vbox==equiv(every_vbox_loc)
  4045. @d every_job==equiv(every_job_loc)
  4046. @d every_cr==equiv(every_cr_loc)
  4047. @d err_help==equiv(err_help_loc)
  4048. @d toks(#)==equiv(toks_base+#)
  4049. @d box(#)==equiv(box_base+#)
  4050. @d cur_font==equiv(cur_font_loc)
  4051. @d fam_fnt(#)==equiv(math_font_base+#)
  4052. @d cat_code(#)==equiv(cat_code_base+#)
  4053. @d lc_code(#)==equiv(lc_code_base+#)
  4054. @d uc_code(#)==equiv(uc_code_base+#)
  4055. @d sf_code(#)==equiv(sf_code_base+#)
  4056. @d math_code(#)==equiv(math_code_base+#)
  4057.   {Note: |math_code(c)| is the true math code plus |min_halfword|}
  4058. @<Put each...@>=
  4059. primitive("output",assign_toks,output_routine_loc);
  4060. @!@:output_}{\.{\\output} primitive@>
  4061. primitive("everypar",assign_toks,every_par_loc);
  4062. @!@:every_par_}{\.{\\everypar} primitive@>
  4063. primitive("everymath",assign_toks,every_math_loc);
  4064. @!@:every_math_}{\.{\\everymath} primitive@>
  4065. primitive("everydisplay",assign_toks,every_display_loc);
  4066. @!@:every_display_}{\.{\\everydisplay} primitive@>
  4067. primitive("everyhbox",assign_toks,every_hbox_loc);
  4068. @!@:every_hbox_}{\.{\\everyhbox} primitive@>
  4069. primitive("everyvbox",assign_toks,every_vbox_loc);
  4070. @!@:every_vbox_}{\.{\\everyvbox} primitive@>
  4071. primitive("everyjob",assign_toks,every_job_loc);
  4072. @!@:every_job_}{\.{\\everyjob} primitive@>
  4073. primitive("everycr",assign_toks,every_cr_loc);
  4074. @!@:every_cr_}{\.{\\everycr} primitive@>
  4075. primitive("errhelp",assign_toks,err_help_loc);
  4076. @!@:err_help_}{\.{\\errhelp} primitive@>
  4077. @ @<Cases of |print_cmd_chr|...@>=
  4078. assign_toks: if chr_code>=toks_base then
  4079.   begin print_esc("toks"); print_int(chr_code-toks_base);
  4080.   end
  4081. else  case chr_code of
  4082.   output_routine_loc: print_esc("output");
  4083.   every_par_loc: print_esc("everypar");
  4084.   every_math_loc: print_esc("everymath");
  4085.   every_display_loc: print_esc("everydisplay");
  4086.   every_hbox_loc: print_esc("everyhbox");
  4087.   every_vbox_loc: print_esc("everyvbox");
  4088.   every_job_loc: print_esc("everyjob");
  4089.   every_cr_loc: print_esc("everycr");
  4090.   othercases print_esc("errhelp")
  4091.   endcases;
  4092. @ We initialize most things to null or undefined values. An undefined font
  4093. is represented by the internal code |font_base|.
  4094. However, the character code tables are given initial values based on the
  4095. conventional interpretation of ASCII code. These initial values should
  4096. not be changed when \TeX\ is adapted for use with non-English languages;
  4097. all changes to the initialization conventions should be made in format
  4098. packages, not in \TeX\ itself, so that global interchange of formats is
  4099. possible.
  4100. @d null_font==font_base
  4101. @d var_code==@'70000 {math code meaning ``use the current family''}
  4102. @<Initialize table entries...@>=
  4103. par_shape_ptr:=null; eq_type(par_shape_loc):=shape_ref;
  4104. eq_level(par_shape_loc):=level_one;@/
  4105. for k:=output_routine_loc to toks_base+255 do
  4106.   eqtb[k]:=eqtb[undefined_control_sequence];
  4107. box(0):=null; eq_type(box_base):=box_ref; eq_level(box_base):=level_one;
  4108. for k:=box_base+1 to box_base+255 do eqtb[k]:=eqtb[box_base];
  4109. cur_font:=null_font; eq_type(cur_font_loc):=data;
  4110. eq_level(cur_font_loc):=level_one;@/
  4111. for k:=math_font_base to math_font_base+47 do eqtb[k]:=eqtb[cur_font_loc];
  4112. equiv(cat_code_base):=0; eq_type(cat_code_base):=data;
  4113. eq_level(cat_code_base):=level_one;@/
  4114. for k:=cat_code_base+1 to int_base-1 do eqtb[k]:=eqtb[cat_code_base];
  4115. for k:=0 to 255 do
  4116.   begin cat_code(k):=other_char; math_code(k):=hi(k); sf_code(k):=1000;
  4117.   end;
  4118. cat_code(carriage_return):=car_ret; cat_code(" "):=spacer;
  4119. cat_code("\"):=escape; cat_code("%"):=comment;
  4120. cat_code(invalid_code):=invalid_char; cat_code(null_code):=ignore;
  4121. for k:="0" to "9" do math_code(k):=hi(k+var_code);
  4122. for k:="A" to "Z" do
  4123.   begin cat_code(k):=letter; cat_code(k+"a"-"A"):=letter;@/
  4124.   math_code(k):=hi(k+var_code+@"100);
  4125.   math_code(k+"a"-"A"):=hi(k+"a"-"A"+var_code+@"100);@/
  4126.   lc_code(k):=k+"a"-"A"; lc_code(k+"a"-"A"):=k+"a"-"A";@/
  4127.   uc_code(k):=k; uc_code(k+"a"-"A"):=k;@/
  4128.   sf_code(k):=999;
  4129.   end;
  4130. @ @<Show equivalent |n|, in region 4@>=
  4131. if n=par_shape_loc then
  4132.   begin print_esc("parshape"); print_char("=");
  4133.   if par_shape_ptr=null then print_char("0")
  4134.   else print_int(info(par_shape_ptr));
  4135.   end
  4136. else if n<toks_base then
  4137.   begin print_cmd_chr(assign_toks,n); print_char("=");
  4138.   if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
  4139.   end
  4140. else if n<box_base then
  4141.   begin print_esc("toks"); print_int(n-toks_base); print_char("=");
  4142.   if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
  4143.   end
  4144. else if n<cur_font_loc then
  4145.   begin print_esc("box"); print_int(n-box_base); print_char("=");
  4146.   if equiv(n)=null then print("void")
  4147.   else  begin depth_threshold:=0; breadth_max:=1; show_node_list(equiv(n));
  4148.     end;
  4149.   end
  4150. else if n<cat_code_base then @<Show the font identifier in |eqtb[n]|@>
  4151. else @<Show the halfword code in |eqtb[n]|@>
  4152. @ @<Show the font identifier in |eqtb[n]|@>=
  4153. begin if n=cur_font_loc then print("current font")
  4154. else if n<math_font_base+16 then
  4155.   begin print_esc("textfont"); print_int(n-math_font_base);
  4156.   end
  4157. else if n<math_font_base+32 then
  4158.   begin print_esc("scriptfont"); print_int(n-math_font_base-16);
  4159.   end
  4160. else  begin print_esc("scriptscriptfont"); print_int(n-math_font_base-32);
  4161.   end;
  4162. print_char("=");@/
  4163. print_esc(hash[font_id_base+equiv(n)].rh);
  4164.   {that's |font_id_text(equiv(n))|}
  4165. @ @<Show the halfword code in |eqtb[n]|@>=
  4166. if n<math_code_base then
  4167.   begin if n<lc_code_base then
  4168.     begin print_esc("catcode"); print_int(n-cat_code_base);
  4169.     end
  4170.   else if n<uc_code_base then
  4171.     begin print_esc("lccode"); print_int(n-lc_code_base);
  4172.     end
  4173.   else if n<sf_code_base then
  4174.     begin print_esc("uccode"); print_int(n-uc_code_base);
  4175.     end
  4176.   else  begin print_esc("sfcode"); print_int(n-sf_code_base);
  4177.     end;
  4178.   print_char("="); print_int(equiv(n));
  4179.   end
  4180. else  begin print_esc("mathcode"); print_int(n-math_code_base);
  4181.   print_char("="); print_int(ho(equiv(n)));
  4182.   end
  4183. @ Region 5 of |eqtb| contains the integer parameters and registers defined
  4184. here, as well as the |del_code| table. The latter table differs from the
  4185. |cat_code..math_code| tables that precede it, since delimiter codes are
  4186. fullword integers while the other kinds of codes occupy at most a
  4187. halfword. This is what makes region~5 different from region~4. We will
  4188. store the |eq_level| information in an auxiliary array of quarterwords
  4189. that will be defined later.
  4190. @d pretolerance_code=0 {badness tolerance before hyphenation}
  4191. @d tolerance_code=1 {badness tolerance after hyphenation}
  4192. @d line_penalty_code=2 {added to the badness of every line}
  4193. @d hyphen_penalty_code=3 {penalty for break after discretionary hyphen}
  4194. @d ex_hyphen_penalty_code=4 {penalty for break after explicit hyphen}
  4195. @d club_penalty_code=5 {penalty for creating a club line}
  4196. @d widow_penalty_code=6 {penalty for creating a widow line}
  4197. @d display_widow_penalty_code=7 {ditto, just before a display}
  4198. @d broken_penalty_code=8 {penalty for breaking a page at a broken line}
  4199. @d bin_op_penalty_code=9 {penalty for breaking after a binary operation}
  4200. @d rel_penalty_code=10 {penalty for breaking after a relation}
  4201. @d pre_display_penalty_code=11
  4202.   {penalty for breaking just before a displayed formula}
  4203. @d post_display_penalty_code=12
  4204.   {penalty for breaking just after a displayed formula}
  4205. @d inter_line_penalty_code=13 {additional penalty between lines}
  4206. @d double_hyphen_demerits_code=14 {demerits for double hyphen break}
  4207. @d final_hyphen_demerits_code=15 {demerits for final hyphen break}
  4208. @d adj_demerits_code=16 {demerits for adjacent incompatible lines}
  4209. @d mag_code=17 {magnification ratio}
  4210. @d delimiter_factor_code=18 {ratio for variable-size delimiters}
  4211. @d looseness_code=19 {change in number of lines for a paragraph}
  4212. @d time_code=20 {current time of day}
  4213. @d day_code=21 {current day of the month}
  4214. @d month_code=22 {current month of the year}
  4215. @d year_code=23 {current year of our Lord}
  4216. @d show_box_breadth_code=24 {nodes per level in |show_box|}
  4217. @d show_box_depth_code=25 {maximum level in |show_box|}
  4218. @d hbadness_code=26 {hboxes exceeding this badness will be shown by |hpack|}
  4219. @d vbadness_code=27 {vboxes exceeding this badness will be shown by |vpack|}
  4220. @d pausing_code=28 {pause after each line is read from a file}
  4221. @d tracing_online_code=29 {show diagnostic output on terminal}
  4222. @d tracing_macros_code=30 {show macros as they are being expanded}
  4223. @d tracing_stats_code=31 {show memory usage if \TeX\ knows it}
  4224. @d tracing_paragraphs_code=32 {show line-break calculations}
  4225. @d tracing_pages_code=33 {show page-break calculations}
  4226. @d tracing_output_code=34 {show boxes when they are shipped out}
  4227. @d tracing_lost_chars_code=35 {show characters that aren't in the font}
  4228. @d tracing_commands_code=36 {show command codes at |big_switch|}
  4229. @d tracing_restores_code=37 {show equivalents when they are restored}
  4230. @d uc_hyph_code=38 {hyphenate words beginning with a capital letter}
  4231. @d output_penalty_code=39 {penalty found at current page break}
  4232. @d max_dead_cycles_code=40 {bound on consecutive dead cycles of output}
  4233. @d hang_after_code=41 {hanging indentation changes after this many lines}
  4234. @d floating_penalty_code=42 {penalty for insertions heldover after a split}
  4235. @d global_defs_code=43 {override \.{\\global} specifications}
  4236. @d cur_fam_code=44 {current family}
  4237. @d escape_char_code=45 {escape character for token output}
  4238. @d default_hyphen_char_code=46 {value of \.{\\hyphenchar} when a font is loaded}
  4239. @d default_skew_char_code=47 {value of \.{\\skewchar} when a font is loaded}
  4240. @d end_line_char_code=48 {character placed at the right end of the buffer}
  4241. @d new_line_char_code=49 {character that prints as |print_ln|}
  4242. @d language_code=50 {current hyphenation table}
  4243. @d left_hyphen_min_code=51 {minimum left hyphenation fragment size}
  4244. @d right_hyphen_min_code=52 {minimum right hyphenation fragment size}
  4245. @d holding_inserts_code=53 {do not remove insertion nodes from \.{\\box255}}
  4246. @d error_context_lines_code=54 {maximum intermediate line pairs shown}
  4247. @d int_pars=55 {total number of integer parameters}
  4248. @d count_base=int_base+int_pars {256 user \.{\\count} registers}
  4249. @d del_code_base=count_base+256 {256 delimiter code mappings}
  4250. @d dimen_base=del_code_base+256 {beginning of region 6}
  4251. @d del_code(#)==eqtb[del_code_base+#].int
  4252. @d count(#)==eqtb[count_base+#].int
  4253. @d int_par(#)==eqtb[int_base+#].int {an integer parameter}
  4254. @d pretolerance==int_par(pretolerance_code)
  4255. @d tolerance==int_par(tolerance_code)
  4256. @d line_penalty==int_par(line_penalty_code)
  4257. @d hyphen_penalty==int_par(hyphen_penalty_code)
  4258. @d ex_hyphen_penalty==int_par(ex_hyphen_penalty_code)
  4259. @d club_penalty==int_par(club_penalty_code)
  4260. @d widow_penalty==int_par(widow_penalty_code)
  4261. @d display_widow_penalty==int_par(display_widow_penalty_code)
  4262. @d broken_penalty==int_par(broken_penalty_code)
  4263. @d bin_op_penalty==int_par(bin_op_penalty_code)
  4264. @d rel_penalty==int_par(rel_penalty_code)
  4265. @d pre_display_penalty==int_par(pre_display_penalty_code)
  4266. @d post_display_penalty==int_par(post_display_penalty_code)
  4267. @d inter_line_penalty==int_par(inter_line_penalty_code)
  4268. @d double_hyphen_demerits==int_par(double_hyphen_demerits_code)
  4269. @d final_hyphen_demerits==int_par(final_hyphen_demerits_code)
  4270. @d adj_demerits==int_par(adj_demerits_code)
  4271. @d mag==int_par(mag_code)
  4272. @d delimiter_factor==int_par(delimiter_factor_code)
  4273. @d looseness==int_par(looseness_code)
  4274. @d time==int_par(time_code)
  4275. @d day==int_par(day_code)
  4276. @d month==int_par(month_code)
  4277. @d year==int_par(year_code)
  4278. @d show_box_breadth==int_par(show_box_breadth_code)
  4279. @d show_box_depth==int_par(show_box_depth_code)
  4280. @d hbadness==int_par(hbadness_code)
  4281. @d vbadness==int_par(vbadness_code)
  4282. @d pausing==int_par(pausing_code)
  4283. @d tracing_online==int_par(tracing_online_code)
  4284. @d tracing_macros==int_par(tracing_macros_code)
  4285. @d tracing_stats==int_par(tracing_stats_code)
  4286. @d tracing_paragraphs==int_par(tracing_paragraphs_code)
  4287. @d tracing_pages==int_par(tracing_pages_code)
  4288. @d tracing_output==int_par(tracing_output_code)
  4289. @d tracing_lost_chars==int_par(tracing_lost_chars_code)
  4290. @d tracing_commands==int_par(tracing_commands_code)
  4291. @d tracing_restores==int_par(tracing_restores_code)
  4292. @d uc_hyph==int_par(uc_hyph_code)
  4293. @d output_penalty==int_par(output_penalty_code)
  4294. @d max_dead_cycles==int_par(max_dead_cycles_code)
  4295. @d hang_after==int_par(hang_after_code)
  4296. @d floating_penalty==int_par(floating_penalty_code)
  4297. @d global_defs==int_par(global_defs_code)
  4298. @d cur_fam==int_par(cur_fam_code)
  4299. @d escape_char==int_par(escape_char_code)
  4300. @d default_hyphen_char==int_par(default_hyphen_char_code)
  4301. @d default_skew_char==int_par(default_skew_char_code)
  4302. @d end_line_char==int_par(end_line_char_code)
  4303. @d new_line_char==int_par(new_line_char_code)
  4304. @d language==int_par(language_code)
  4305. @d left_hyphen_min==int_par(left_hyphen_min_code)
  4306. @d right_hyphen_min==int_par(right_hyphen_min_code)
  4307. @d holding_inserts==int_par(holding_inserts_code)
  4308. @d error_context_lines==int_par(error_context_lines_code)
  4309. @<Assign the values |depth_threshold:=show_box_depth|...@>=
  4310. depth_threshold:=show_box_depth;
  4311. breadth_max:=show_box_breadth
  4312. @ We can print the symbolic name of an integer parameter as follows.
  4313. @p procedure print_param(@!n:integer);
  4314. begin case n of
  4315. pretolerance_code:print_esc("pretolerance");
  4316. tolerance_code:print_esc("tolerance");
  4317. line_penalty_code:print_esc("linepenalty");
  4318. hyphen_penalty_code:print_esc("hyphenpenalty");
  4319. ex_hyphen_penalty_code:print_esc("exhyphenpenalty");
  4320. club_penalty_code:print_esc("clubpenalty");
  4321. widow_penalty_code:print_esc("widowpenalty");
  4322. display_widow_penalty_code:print_esc("displaywidowpenalty");
  4323. broken_penalty_code:print_esc("brokenpenalty");
  4324. bin_op_penalty_code:print_esc("binoppenalty");
  4325. rel_penalty_code:print_esc("relpenalty");
  4326. pre_display_penalty_code:print_esc("predisplaypenalty");
  4327. post_display_penalty_code:print_esc("postdisplaypenalty");
  4328. inter_line_penalty_code:print_esc("interlinepenalty");
  4329. double_hyphen_demerits_code:print_esc("doublehyphendemerits");
  4330. final_hyphen_demerits_code:print_esc("finalhyphendemerits");
  4331. adj_demerits_code:print_esc("adjdemerits");
  4332. mag_code:print_esc("mag");
  4333. delimiter_factor_code:print_esc("delimiterfactor");
  4334. looseness_code:print_esc("looseness");
  4335. time_code:print_esc("time");
  4336. day_code:print_esc("day");
  4337. month_code:print_esc("month");
  4338. year_code:print_esc("year");
  4339. show_box_breadth_code:print_esc("showboxbreadth");
  4340. show_box_depth_code:print_esc("showboxdepth");
  4341. hbadness_code:print_esc("hbadness");
  4342. vbadness_code:print_esc("vbadness");
  4343. pausing_code:print_esc("pausing");
  4344. tracing_online_code:print_esc("tracingonline");
  4345. tracing_macros_code:print_esc("tracingmacros");
  4346. tracing_stats_code:print_esc("tracingstats");
  4347. tracing_paragraphs_code:print_esc("tracingparagraphs");
  4348. tracing_pages_code:print_esc("tracingpages");
  4349. tracing_output_code:print_esc("tracingoutput");
  4350. tracing_lost_chars_code:print_esc("tracinglostchars");
  4351. tracing_commands_code:print_esc("tracingcommands");
  4352. tracing_restores_code:print_esc("tracingrestores");
  4353. uc_hyph_code:print_esc("uchyph");
  4354. output_penalty_code:print_esc("outputpenalty");
  4355. max_dead_cycles_code:print_esc("maxdeadcycles");
  4356. hang_after_code:print_esc("hangafter");
  4357. floating_penalty_code:print_esc("floatingpenalty");
  4358. global_defs_code:print_esc("globaldefs");
  4359. cur_fam_code:print_esc("fam");
  4360. escape_char_code:print_esc("escapechar");
  4361. default_hyphen_char_code:print_esc("defaulthyphenchar");
  4362. default_skew_char_code:print_esc("defaultskewchar");
  4363. end_line_char_code:print_esc("endlinechar");
  4364. new_line_char_code:print_esc("newlinechar");
  4365. language_code:print_esc("language");
  4366. left_hyphen_min_code:print_esc("lefthyphenmin");
  4367. right_hyphen_min_code:print_esc("righthyphenmin");
  4368. holding_inserts_code:print_esc("holdinginserts");
  4369. error_context_lines_code:print_esc("errorcontextlines");
  4370. othercases print("[unknown integer parameter!]")
  4371. endcases;
  4372. @ The integer parameter names must be entered into the hash table.
  4373. @<Put each...@>=
  4374. primitive("pretolerance",assign_int,int_base+pretolerance_code);@/
  4375. @!@:pretolerance_}{\.{\\pretolerance} primitive@>
  4376. primitive("tolerance",assign_int,int_base+tolerance_code);@/
  4377. @!@:tolerance_}{\.{\\tolerance} primitive@>
  4378. primitive("linepenalty",assign_int,int_base+line_penalty_code);@/
  4379. @!@:line_penalty_}{\.{\\linepenalty} primitive@>
  4380. primitive("hyphenpenalty",assign_int,int_base+hyphen_penalty_code);@/
  4381. @!@:hyphen_penalty_}{\.{\\hyphenpenalty} primitive@>
  4382. primitive("exhyphenpenalty",assign_int,int_base+ex_hyphen_penalty_code);@/
  4383. @!@:ex_hyphen_penalty_}{\.{\\exhyphenpenalty} primitive@>
  4384. primitive("clubpenalty",assign_int,int_base+club_penalty_code);@/
  4385. @!@:club_penalty_}{\.{\\clubpenalty} primitive@>
  4386. primitive("widowpenalty",assign_int,int_base+widow_penalty_code);@/
  4387. @!@:widow_penalty_}{\.{\\widowpenalty} primitive@>
  4388. primitive("displaywidowpenalty",
  4389.   assign_int,int_base+display_widow_penalty_code);@/
  4390. @!@:display_widow_penalty_}{\.{\\displaywidowpenalty} primitive@>
  4391. primitive("brokenpenalty",assign_int,int_base+broken_penalty_code);@/
  4392. @!@:broken_penalty_}{\.{\\brokenpenalty} primitive@>
  4393. primitive("binoppenalty",assign_int,int_base+bin_op_penalty_code);@/
  4394. @!@:bin_op_penalty_}{\.{\\binoppenalty} primitive@>
  4395. primitive("relpenalty",assign_int,int_base+rel_penalty_code);@/
  4396. @!@:rel_penalty_}{\.{\\relpenalty} primitive@>
  4397. primitive("predisplaypenalty",assign_int,int_base+pre_display_penalty_code);@/
  4398. @!@:pre_display_penalty_}{\.{\\predisplaypenalty} primitive@>
  4399. primitive("postdisplaypenalty",assign_int,int_base+post_display_penalty_code);@/
  4400. @!@:post_display_penalty_}{\.{\\postdisplaypenalty} primitive@>
  4401. primitive("interlinepenalty",assign_int,int_base+inter_line_penalty_code);@/
  4402. @!@:inter_line_penalty_}{\.{\\interlinepenalty} primitive@>
  4403. primitive("doublehyphendemerits",
  4404.   assign_int,int_base+double_hyphen_demerits_code);@/
  4405. @!@:double_hyphen_demerits_}{\.{\\doublehyphendemerits} primitive@>
  4406. primitive("finalhyphendemerits",
  4407.   assign_int,int_base+final_hyphen_demerits_code);@/
  4408. @!@:final_hyphen_demerits_}{\.{\\finalhyphendemerits} primitive@>
  4409. primitive("adjdemerits",assign_int,int_base+adj_demerits_code);@/
  4410. @!@:adj_demerits_}{\.{\\adjdemerits} primitive@>
  4411. primitive("mag",assign_int,int_base+mag_code);@/
  4412. @!@:mag_}{\.{\\mag} primitive@>
  4413. primitive("delimiterfactor",assign_int,int_base+delimiter_factor_code);@/
  4414. @!@:delimiter_factor_}{\.{\\delimiterfactor} primitive@>
  4415. primitive("looseness",assign_int,int_base+looseness_code);@/
  4416. @!@:looseness_}{\.{\\looseness} primitive@>
  4417. primitive("time",assign_int,int_base+time_code);@/
  4418. @!@:time_}{\.{\\time} primitive@>
  4419. primitive("day",assign_int,int_base+day_code);@/
  4420. @!@:day_}{\.{\\day} primitive@>
  4421. primitive("month",assign_int,int_base+month_code);@/
  4422. @!@:month_}{\.{\\month} primitive@>
  4423. primitive("year",assign_int,int_base+year_code);@/
  4424. @!@:year_}{\.{\\year} primitive@>
  4425. primitive("showboxbreadth",assign_int,int_base+show_box_breadth_code);@/
  4426. @!@:show_box_breadth_}{\.{\\showboxbreadth} primitive@>
  4427. primitive("showboxdepth",assign_int,int_base+show_box_depth_code);@/
  4428. @!@:show_box_depth_}{\.{\\showboxdepth} primitive@>
  4429. primitive("hbadness",assign_int,int_base+hbadness_code);@/
  4430. @!@:hbadness_}{\.{\\hbadness} primitive@>
  4431. primitive("vbadness",assign_int,int_base+vbadness_code);@/
  4432. @!@:vbadness_}{\.{\\vbadness} primitive@>
  4433. primitive("pausing",assign_int,int_base+pausing_code);@/
  4434. @!@:pausing_}{\.{\\pausing} primitive@>
  4435. primitive("tracingonline",assign_int,int_base+tracing_online_code);@/
  4436. @!@:tracing_online_}{\.{\\tracingonline} primitive@>
  4437. primitive("tracingmacros",assign_int,int_base+tracing_macros_code);@/
  4438. @!@:tracing_macros_}{\.{\\tracingmacros} primitive@>
  4439. primitive("tracingstats",assign_int,int_base+tracing_stats_code);@/
  4440. @!@:tracing_stats_}{\.{\\tracingstats} primitive@>
  4441. primitive("tracingparagraphs",assign_int,int_base+tracing_paragraphs_code);@/
  4442. @!@:tracing_paragraphs_}{\.{\\tracingparagraphs} primitive@>
  4443. primitive("tracingpages",assign_int,int_base+tracing_pages_code);@/
  4444. @!@:tracing_pages_}{\.{\\tracingpages} primitive@>
  4445. primitive("tracingoutput",assign_int,int_base+tracing_output_code);@/
  4446. @!@:tracing_output_}{\.{\\tracingoutput} primitive@>
  4447. primitive("tracinglostchars",assign_int,int_base+tracing_lost_chars_code);@/
  4448. @!@:tracing_lost_chars_}{\.{\\tracinglostchars} primitive@>
  4449. primitive("tracingcommands",assign_int,int_base+tracing_commands_code);@/
  4450. @!@:tracing_commands_}{\.{\\tracingcommands} primitive@>
  4451. primitive("tracingrestores",assign_int,int_base+tracing_restores_code);@/
  4452. @!@:tracing_restores_}{\.{\\tracingrestores} primitive@>
  4453. primitive("uchyph",assign_int,int_base+uc_hyph_code);@/
  4454. @!@:uc_hyph_}{\.{\\uchyph} primitive@>
  4455. primitive("outputpenalty",assign_int,int_base+output_penalty_code);@/
  4456. @!@:output_penalty_}{\.{\\outputpenalty} primitive@>
  4457. primitive("maxdeadcycles",assign_int,int_base+max_dead_cycles_code);@/
  4458. @!@:max_dead_cycles_}{\.{\\maxdeadcycles} primitive@>
  4459. primitive("hangafter",assign_int,int_base+hang_after_code);@/
  4460. @!@:hang_after_}{\.{\\hangafter} primitive@>
  4461. primitive("floatingpenalty",assign_int,int_base+floating_penalty_code);@/
  4462. @!@:floating_penalty_}{\.{\\floatingpenalty} primitive@>
  4463. primitive("globaldefs",assign_int,int_base+global_defs_code);@/
  4464. @!@:global_defs_}{\.{\\globaldefs} primitive@>
  4465. primitive("fam",assign_int,int_base+cur_fam_code);@/
  4466. @!@:fam_}{\.{\\fam} primitive@>
  4467. primitive("escapechar",assign_int,int_base+escape_char_code);@/
  4468. @!@:escape_char_}{\.{\\escapechar} primitive@>
  4469. primitive("defaulthyphenchar",assign_int,int_base+default_hyphen_char_code);@/
  4470. @!@:default_hyphen_char_}{\.{\\defaulthyphenchar} primitive@>
  4471. primitive("defaultskewchar",assign_int,int_base+default_skew_char_code);@/
  4472. @!@:default_skew_char_}{\.{\\defaultskewchar} primitive@>
  4473. primitive("endlinechar",assign_int,int_base+end_line_char_code);@/
  4474. @!@:end_line_char_}{\.{\\endlinechar} primitive@>
  4475. primitive("newlinechar",assign_int,int_base+new_line_char_code);@/
  4476. @!@:new_line_char_}{\.{\\newlinechar} primitive@>
  4477. primitive("language",assign_int,int_base+language_code);@/
  4478. @!@:language_}{\.{\\language} primitive@>
  4479. primitive("lefthyphenmin",assign_int,int_base+left_hyphen_min_code);@/
  4480. @!@:left_hyphen_min_}{\.{\\lefthyphenmin} primitive@>
  4481. primitive("righthyphenmin",assign_int,int_base+right_hyphen_min_code);@/
  4482. @!@:right_hyphen_min_}{\.{\\righthyphenmin} primitive@>
  4483. primitive("holdinginserts",assign_int,int_base+holding_inserts_code);@/
  4484. @!@:holding_inserts_}{\.{\\holdinginserts} primitive@>
  4485. primitive("errorcontextlines",assign_int,int_base+error_context_lines_code);@/
  4486. @!@:error_context_lines_}{\.{\\errorcontextlines} primitive@>
  4487. @ @<Cases of |print_cmd_chr|...@>=
  4488. assign_int: if chr_code<count_base then print_param(chr_code-int_base)
  4489.   else  begin print_esc("count"); print_int(chr_code-count_base);
  4490.     end;
  4491. @ The integer parameters should really be initialized by a macro package;
  4492. the following initialization does the minimum to keep \TeX\ from
  4493. complete failure.
  4494. @^null delimiter@>
  4495. @<Initialize table entries...@>=
  4496. for k:=int_base to del_code_base-1 do eqtb[k].int:=0;
  4497. mag:=1000; tolerance:=10000; hang_after:=1; max_dead_cycles:=25;
  4498. escape_char:="\"; end_line_char:=carriage_return;
  4499. for k:=0 to 255 do del_code(k):=-1;
  4500. del_code("."):=0; {this null delimiter is used in error recovery}
  4501. @ The following procedure, which is called just before \TeX\ initializes its
  4502. input and output, establishes the initial values of the date and time.
  4503. @^system dependencies@>
  4504. Since standard \PASCAL\ cannot provide such information, something special
  4505. is needed. The program here simply specifies July 4, 1776, at noon; but
  4506. users probably want a better approximation to the truth.
  4507. @p procedure fix_date_and_time;
  4508. begin time:=12*60; {minutes since midnight}
  4509. day:=4; {fourth day of the month}
  4510. month:=7; {seventh month of the year}
  4511. year:=1776; {Anno Domini}
  4512. @ @<Show equivalent |n|, in region 5@>=
  4513. begin if n<count_base then print_param(n-int_base)
  4514. else if  n<del_code_base then
  4515.   begin print_esc("count"); print_int(n-count_base);
  4516.   end
  4517. else  begin print_esc("delcode"); print_int(n-del_code_base);
  4518.   end;
  4519. print_char("="); print_int(eqtb[n].int);
  4520. @ @<Set variable |c| to the current escape character@>=c:=escape_char
  4521. @ @<Character |s| is the current new-line character@>=s=new_line_char
  4522. @ \TeX\ is occasionally supposed to print diagnostic information that
  4523. goes only into the transcript file, unless |tracing_online| is positive.
  4524. Here are two routines that adjust the destination of print commands:
  4525. @p procedure begin_diagnostic; {prepare to do some tracing}
  4526. begin old_setting:=selector;
  4527. if (tracing_online<=0)and(selector=term_and_log) then
  4528.   begin decr(selector);
  4529.   if history=spotless then history:=warning_issued;
  4530.   end;
  4531. procedure end_diagnostic(@!blank_line:boolean);
  4532.   {restore proper conditions after tracing}
  4533. begin print_nl("");
  4534. if blank_line then print_ln;
  4535. selector:=old_setting;
  4536. @ Of course we had better declare another global variable, if the previous
  4537. routines are going to work.
  4538. @<Glob...@>=
  4539. @!old_setting:0..max_selector;
  4540. @ The final region of |eqtb| contains the dimension parameters defined
  4541. here, and the 256 \.{\\dimen} registers.
  4542. @d par_indent_code=0 {indentation of paragraphs}
  4543. @d math_surround_code=1 {space around math in text}
  4544. @d line_skip_limit_code=2 {threshold for |line_skip| instead of |baseline_skip|}
  4545. @d hsize_code=3 {line width in horizontal mode}
  4546. @d vsize_code=4 {page height in vertical mode}
  4547. @d max_depth_code=5 {maximum depth of boxes on main pages}
  4548. @d split_max_depth_code=6 {maximum depth of boxes on split pages}
  4549. @d box_max_depth_code=7 {maximum depth of explicit vboxes}
  4550. @d hfuzz_code=8 {tolerance for overfull hbox messages}
  4551. @d vfuzz_code=9 {tolerance for overfull vbox messages}
  4552. @d delimiter_shortfall_code=10 {maximum amount uncovered by variable delimiters}
  4553. @d null_delimiter_space_code=11 {blank space in null delimiters}
  4554. @d script_space_code=12 {extra space after subscript or superscript}
  4555. @d pre_display_size_code=13 {length of text preceding a display}
  4556. @d display_width_code=14 {length of line for displayed equation}
  4557. @d display_indent_code=15 {indentation of line for displayed equation}
  4558. @d overfull_rule_code=16 {width of rule that identifies overfull hboxes}
  4559. @d hang_indent_code=17 {amount of hanging indentation}
  4560. @d h_offset_code=18 {amount of horizontal offset when shipping pages out}
  4561. @d v_offset_code=19 {amount of vertical offset when shipping pages out}
  4562. @d emergency_stretch_code=20 {reduces badnesses on final pass of line-breaking}
  4563. @d dimen_pars=21 {total number of dimension parameters}
  4564. @d scaled_base=dimen_base+dimen_pars
  4565.   {table of 256 user-defined \.{\\dimen} registers}
  4566. @d eqtb_size=scaled_base+255 {largest subscript of |eqtb|}
  4567. @d dimen(#)==eqtb[scaled_base+#].sc
  4568. @d dimen_par(#)==eqtb[dimen_base+#].sc {a scaled quantity}
  4569. @d par_indent==dimen_par(par_indent_code)
  4570. @d math_surround==dimen_par(math_surround_code)
  4571. @d line_skip_limit==dimen_par(line_skip_limit_code)
  4572. @d hsize==dimen_par(hsize_code)
  4573. @d vsize==dimen_par(vsize_code)
  4574. @d max_depth==dimen_par(max_depth_code)
  4575. @d split_max_depth==dimen_par(split_max_depth_code)
  4576. @d box_max_depth==dimen_par(box_max_depth_code)
  4577. @d hfuzz==dimen_par(hfuzz_code)
  4578. @d vfuzz==dimen_par(vfuzz_code)
  4579. @d delimiter_shortfall==dimen_par(delimiter_shortfall_code)
  4580. @d null_delimiter_space==dimen_par(null_delimiter_space_code)
  4581. @d script_space==dimen_par(script_space_code)
  4582. @d pre_display_size==dimen_par(pre_display_size_code)
  4583. @d display_width==dimen_par(display_width_code)
  4584. @d display_indent==dimen_par(display_indent_code)
  4585. @d overfull_rule==dimen_par(overfull_rule_code)
  4586. @d hang_indent==dimen_par(hang_indent_code)
  4587. @d h_offset==dimen_par(h_offset_code)
  4588. @d v_offset==dimen_par(v_offset_code)
  4589. @d emergency_stretch==dimen_par(emergency_stretch_code)
  4590. @p procedure print_length_param(@!n:integer);
  4591. begin case n of
  4592. par_indent_code:print_esc("parindent");
  4593. math_surround_code:print_esc("mathsurround");
  4594. line_skip_limit_code:print_esc("lineskiplimit");
  4595. hsize_code:print_esc("hsize");
  4596. vsize_code:print_esc("vsize");
  4597. max_depth_code:print_esc("maxdepth");
  4598. split_max_depth_code:print_esc("splitmaxdepth");
  4599. box_max_depth_code:print_esc("boxmaxdepth");
  4600. hfuzz_code:print_esc("hfuzz");
  4601. vfuzz_code:print_esc("vfuzz");
  4602. delimiter_shortfall_code:print_esc("delimitershortfall");
  4603. null_delimiter_space_code:print_esc("nulldelimiterspace");
  4604. script_space_code:print_esc("scriptspace");
  4605. pre_display_size_code:print_esc("predisplaysize");
  4606. display_width_code:print_esc("displaywidth");
  4607. display_indent_code:print_esc("displayindent");
  4608. overfull_rule_code:print_esc("overfullrule");
  4609. hang_indent_code:print_esc("hangindent");
  4610. h_offset_code:print_esc("hoffset");
  4611. v_offset_code:print_esc("voffset");
  4612. emergency_stretch_code:print_esc("emergencystretch");
  4613. othercases print("[unknown dimen parameter!]")
  4614. endcases;
  4615. @ @<Put each...@>=
  4616. primitive("parindent",assign_dimen,dimen_base+par_indent_code);@/
  4617. @!@:par_indent_}{\.{\\parindent} primitive@>
  4618. primitive("mathsurround",assign_dimen,dimen_base+math_surround_code);@/
  4619. @!@:math_surround_}{\.{\\mathsurround} primitive@>
  4620. primitive("lineskiplimit",assign_dimen,dimen_base+line_skip_limit_code);@/
  4621. @!@:line_skip_limit_}{\.{\\lineskiplimit} primitive@>
  4622. primitive("hsize",assign_dimen,dimen_base+hsize_code);@/
  4623. @!@:hsize_}{\.{\\hsize} primitive@>
  4624. primitive("vsize",assign_dimen,dimen_base+vsize_code);@/
  4625. @!@:vsize_}{\.{\\vsize} primitive@>
  4626. primitive("maxdepth",assign_dimen,dimen_base+max_depth_code);@/
  4627. @!@:max_depth_}{\.{\\maxdepth} primitive@>
  4628. primitive("splitmaxdepth",assign_dimen,dimen_base+split_max_depth_code);@/
  4629. @!@:split_max_depth_}{\.{\\splitmaxdepth} primitive@>
  4630. primitive("boxmaxdepth",assign_dimen,dimen_base+box_max_depth_code);@/
  4631. @!@:box_max_depth_}{\.{\\boxmaxdepth} primitive@>
  4632. primitive("hfuzz",assign_dimen,dimen_base+hfuzz_code);@/
  4633. @!@:hfuzz_}{\.{\\hfuzz} primitive@>
  4634. primitive("vfuzz",assign_dimen,dimen_base+vfuzz_code);@/
  4635. @!@:vfuzz_}{\.{\\vfuzz} primitive@>
  4636. primitive("delimitershortfall",
  4637.   assign_dimen,dimen_base+delimiter_shortfall_code);@/
  4638. @!@:delimiter_shortfall_}{\.{\\delimitershortfall} primitive@>
  4639. primitive("nulldelimiterspace",
  4640.   assign_dimen,dimen_base+null_delimiter_space_code);@/
  4641. @!@:null_delimiter_space_}{\.{\\nulldelimiterspace} primitive@>
  4642. primitive("scriptspace",assign_dimen,dimen_base+script_space_code);@/
  4643. @!@:script_space_}{\.{\\scriptspace} primitive@>
  4644. primitive("predisplaysize",assign_dimen,dimen_base+pre_display_size_code);@/
  4645. @!@:pre_display_size_}{\.{\\predisplaysize} primitive@>
  4646. primitive("displaywidth",assign_dimen,dimen_base+display_width_code);@/
  4647. @!@:display_width_}{\.{\\displaywidth} primitive@>
  4648. primitive("displayindent",assign_dimen,dimen_base+display_indent_code);@/
  4649. @!@:display_indent_}{\.{\\displayindent} primitive@>
  4650. primitive("overfullrule",assign_dimen,dimen_base+overfull_rule_code);@/
  4651. @!@:overfull_rule_}{\.{\\overfullrule} primitive@>
  4652. primitive("hangindent",assign_dimen,dimen_base+hang_indent_code);@/
  4653. @!@:hang_indent_}{\.{\\hangindent} primitive@>
  4654. primitive("hoffset",assign_dimen,dimen_base+h_offset_code);@/
  4655. @!@:h_offset_}{\.{\\hoffset} primitive@>
  4656. primitive("voffset",assign_dimen,dimen_base+v_offset_code);@/
  4657. @!@:v_offset_}{\.{\\voffset} primitive@>
  4658. primitive("emergencystretch",assign_dimen,dimen_base+emergency_stretch_code);@/
  4659. @!@:emergency_stretch_}{\.{\\emergencystretch} primitive@>
  4660. @ @<Cases of |print_cmd_chr|...@>=
  4661. assign_dimen: if chr_code<scaled_base then
  4662.     print_length_param(chr_code-dimen_base)
  4663.   else  begin print_esc("dimen"); print_int(chr_code-scaled_base);
  4664.     end;
  4665. @ @<Initialize table entries...@>=
  4666. for k:=dimen_base to eqtb_size do eqtb[k].sc:=0;
  4667. @ @<Show equivalent |n|, in region 6@>=
  4668. begin if n<scaled_base then print_length_param(n-dimen_base)
  4669. else  begin print_esc("dimen"); print_int(n-scaled_base);
  4670.   end;
  4671. print_char("="); print_scaled(eqtb[n].sc); print("pt");
  4672. @ Here is a procedure that displays the contents of |eqtb[n]|
  4673. symbolically.
  4674. @p@t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
  4675. @!stat procedure show_eqtb(@!n:pointer);
  4676. begin if n<active_base then print_char("?") {this can't happen}
  4677. else if n<glue_base then @<Show equivalent |n|, in region 1 or 2@>
  4678. else if n<local_base then @<Show equivalent |n|, in region 3@>
  4679. else if n<int_base then @<Show equivalent |n|, in region 4@>
  4680. else if n<dimen_base then @<Show equivalent |n|, in region 5@>
  4681. else if n<=eqtb_size then @<Show equivalent |n|, in region 6@>
  4682. else print_char("?"); {this can't happen either}
  4683. @ The last two regions of |eqtb| have fullword values instead of the
  4684. three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
  4685. but \TeX\ needs to store the |eq_level| information in another array
  4686. called |xeq_level|.
  4687. @<Glob...@>=
  4688. @!eqtb:array[active_base..eqtb_size] of memory_word;
  4689. @!xeq_level:array[int_base..eqtb_size] of quarterword;
  4690. @ @<Set init...@>=
  4691. for k:=int_base to eqtb_size do xeq_level[k]:=level_one;
  4692. @ When the debugging routine |search_mem| is looking for pointers having a
  4693. given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
  4694. first part of region~4.
  4695. @<Search |eqtb| for equivalents equal to |p|@>=
  4696. for q:=active_base to box_base+255 do
  4697.   begin if equiv(q)=p then
  4698.     begin print_nl("EQUIV("); print_int(q); print_char(")");
  4699.     end;
  4700.   end
  4701. @* \[18] The hash table.
  4702. Control sequences are stored and retrieved by means of a fairly standard hash
  4703. table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
  4704. in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
  4705. table, it is never removed, because there are complicated situations
  4706. involving \.{\\gdef} where the removal of a control sequence at the end of
  4707. a group would be a mistake preventable only by the introduction of a
  4708. complicated reference-count mechanism.
  4709. The actual sequence of letters forming a control sequence identifier is
  4710. stored in the |str_pool| array together with all the other strings. An
  4711. auxiliary array |hash| consists of items with two halfword fields per
  4712. word. The first of these, called |next(p)|, points to the next identifier
  4713. belonging to the same coalesced list as the identifier corresponding to~|p|;
  4714. and the other, called |text(p)|, points to the |str_start| entry for
  4715. |p|'s identifier. If position~|p| of the hash table is empty, we have
  4716. |text(p)=0|; if position |p| is either empty or the end of a coalesced
  4717. hash list, we have |next(p)=0|. An auxiliary pointer variable called
  4718. |hash_used| is maintained in such a way that all locations |p>=hash_used|
  4719. are nonempty. The global variable |cs_count| tells how many multiletter
  4720. control sequences have been defined, if statistics are being kept.
  4721. A global boolean variable called |no_new_control_sequence| is set to
  4722. |true| during the time that new hash table entries are forbidden.
  4723. @d next(#) == hash[#].lh {link for coalesced lists}
  4724. @d text(#) == hash[#].rh {string number for control sequence name}
  4725. @d hash_is_full == (hash_used=hash_base) {test if all positions are occupied}
  4726. @d font_id_text(#) == text(font_id_base+#) {a frozen font identifier's name}
  4727. @<Glob...@>=
  4728. @!hash: array[hash_base..undefined_control_sequence-1] of two_halves;
  4729.   {the hash table}
  4730. @!hash_used:pointer; {allocation pointer for |hash|}
  4731. @!no_new_control_sequence:boolean; {are new identifiers legal?}
  4732. @!cs_count:integer; {total number of known identifiers}
  4733. @ @<Set init...@>=
  4734. no_new_control_sequence:=true; {new identifiers are usually forbidden}
  4735. next(hash_base):=0; text(hash_base):=0;
  4736. for k:=hash_base+1 to undefined_control_sequence-1 do hash[k]:=hash[hash_base];
  4737. @ @<Initialize table entries...@>=
  4738. hash_used:=frozen_control_sequence; {nothing is used}
  4739. cs_count:=0;
  4740. eq_type(frozen_dont_expand):=dont_expand;
  4741. text(frozen_dont_expand):="notexpanded:";
  4742. @.notexpanded:@>
  4743. @ Here is the subroutine that searches the hash table for an identifier
  4744. that matches a given string of length |l>1| appearing in |buffer[j..
  4745. (j+l-1)]|. If the identifier is found, the corresponding hash table address
  4746. is returned. Otherwise, if the global variable |no_new_control_sequence|
  4747. is |true|, the dummy address |undefined_control_sequence| is returned.
  4748. Otherwise the identifier is inserted into the hash table and its location
  4749. is returned.
  4750. @p function id_lookup(@!j,@!l:integer):pointer; {search the hash table}
  4751. label found; {go here if you found it}
  4752. var h:integer; {hash code}
  4753. @!d:integer; {number of characters in incomplete current string}
  4754. @!p:pointer; {index in |hash| array}
  4755. @!k:pointer; {index in |buffer| array}
  4756. begin @<Compute the hash code |h|@>;
  4757. p:=h+hash_base; {we start searching here; note that |0<=h<hash_prime|}
  4758. loop@+begin if text(p)>0 then if length(text(p))=l then
  4759.     if str_eq_buf(text(p),j) then goto found;
  4760.   if next(p)=0 then
  4761.     begin if no_new_control_sequence then
  4762.       p:=undefined_control_sequence
  4763.     else @<Insert a new control sequence after |p|, then make
  4764.       |p| point to it@>;
  4765.     goto found;
  4766.     end;
  4767.   p:=next(p);
  4768.   end;
  4769. found: id_lookup:=p;
  4770. @ @<Insert a new control...@>=
  4771. begin if text(p)>0 then
  4772.   begin repeat if hash_is_full then overflow("hash size",hash_size);
  4773. @:TeX capacity exceeded hash size}{\quad hash size@>
  4774.   decr(hash_used);
  4775.   until text(hash_used)=0; {search for an empty location in |hash|}
  4776.   next(p):=hash_used; p:=hash_used;
  4777.   end;
  4778. str_room(l); d:=cur_length;
  4779. while pool_ptr>str_start[str_ptr] do
  4780.   begin decr(pool_ptr); str_pool[pool_ptr+l]:=str_pool[pool_ptr];
  4781.   end; {move current string up to make room for another}
  4782. for k:=j to j+l-1 do append_char(buffer[k]);
  4783. text(p):=make_string; pool_ptr:=pool_ptr+d;
  4784. @!stat incr(cs_count);@+tats@;@/
  4785. @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
  4786. should be a prime number.  The theory of hashing tells us to expect fewer
  4787. than two table probes, on the average, when the search is successful.
  4788. [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
  4789. @^Vitter, Jeffrey Scott@>
  4790. @<Compute the hash code |h|@>=
  4791. h:=buffer[j];
  4792. for k:=j+1 to j+l-1 do
  4793.   begin h:=h+h+buffer[k];
  4794.   while h>=hash_prime do h:=h-hash_prime;
  4795.   end
  4796. @ Single-character control sequences do not need to be looked up in a hash
  4797. table, since we can use the character code itself as a direct address.
  4798. The procedure |print_cs| prints the name of a control sequence, given
  4799. a pointer to its address in |eqtb|. A space is printed after the name
  4800. unless it is a single nonletter or an active character. This procedure
  4801. might be invoked with invalid data, so it is ``extra robust.'' The
  4802. individual characters must be printed one at a time using |print|, since
  4803. they may be unprintable.
  4804. @<Basic printing...@>=
  4805. procedure print_cs(@!p:integer); {prints a purported control sequence}
  4806. begin if p<hash_base then {single character}
  4807.   if p>=single_base then
  4808.     if p=null_cs then
  4809.       begin print_esc("csname"); print_esc("endcsname");
  4810.       end
  4811.     else  begin print_esc(p-single_base);
  4812.       if cat_code(p-single_base)=letter then print_char(" ");
  4813.       end
  4814.   else if p<active_base then print_esc("IMPOSSIBLE.")
  4815. @.IMPOSSIBLE@>
  4816.   else print(p-active_base)
  4817. else if p>=undefined_control_sequence then print_esc("IMPOSSIBLE.")
  4818. else if (text(p)<0)or(text(p)>=str_ptr) then print_esc("NONEXISTENT.")
  4819. @.NONEXISTENT@>
  4820. else  begin print_esc(text(p));
  4821.   print_char(" ");
  4822.   end;
  4823. @ Here is a similar procedure; it avoids the error checks, and it never
  4824. prints a space after the control sequence.
  4825. @<Basic printing procedures@>=
  4826. procedure sprint_cs(@!p:pointer); {prints a control sequence}
  4827. begin if p<hash_base then
  4828.   if p<single_base then print(p-active_base)
  4829.   else  if p<null_cs then print_esc(p-single_base)
  4830.     else  begin print_esc("csname"); print_esc("endcsname");
  4831.       end
  4832. else print_esc(text(p));
  4833. @ We need to put \TeX's ``primitive'' control sequences into the hash
  4834. table, together with their command code (which will be the |eq_type|)
  4835. and an operand (which will be the |equiv|). The |primitive| procedure
  4836. does this, in a way that no \TeX\ user can. The global value |cur_val|
  4837. contains the new |eqtb| pointer after |primitive| has acted.
  4838. @p @!init procedure primitive(@!s:str_number;@!c:quarterword;@!o:halfword);
  4839. var k:pool_pointer; {index into |str_pool|}
  4840. @!j:small_number; {index into |buffer|}
  4841. @!l:small_number; {length of the string}
  4842. begin if s<256 then cur_val:=s+single_base
  4843. else  begin k:=str_start[s]; l:=str_start[s+1]-k;
  4844.     {we will move |s| into the (empty) |buffer|}
  4845.   for j:=0 to l-1 do buffer[j]:=so(str_pool[k+j]);
  4846.   cur_val:=id_lookup(0,l); {|no_new_control_sequence| is |false|}
  4847.   flush_string; text(cur_val):=s; {we don't want to have the string twice}
  4848.   end;
  4849. eq_level(cur_val):=level_one; eq_type(cur_val):=c; equiv(cur_val):=o;
  4850. @ Many of \TeX's primitives need no |equiv|, since they are identifiable
  4851. by their |eq_type| alone. These primitives are loaded into the hash table
  4852. as follows:
  4853. @<Put each of \TeX's primitives into the hash table@>=
  4854. primitive(" ",ex_space,0);@/
  4855. @!@:Single-character primitives /}{\quad\.{\\\ }@>
  4856. primitive("/",ital_corr,0);@/
  4857. @!@:Single-character primitives /}{\quad\.{\\/}@>
  4858. primitive("accent",accent,0);@/
  4859. @!@:accent_}{\.{\\accent} primitive@>
  4860. primitive("advance",advance,0);@/
  4861. @!@:advance_}{\.{\\advance} primitive@>
  4862. primitive("afterassignment",after_assignment,0);@/
  4863. @!@:after_assignment_}{\.{\\afterassignment} primitive@>
  4864. primitive("aftergroup",after_group,0);@/
  4865. @!@:after_group_}{\.{\\aftergroup} primitive@>
  4866. primitive("begingroup",begin_group,0);@/
  4867. @!@:begin_group_}{\.{\\begingroup} primitive@>
  4868. primitive("char",char_num,0);@/
  4869. @!@:char_}{\.{\\char} primitive@>
  4870. primitive("csname",cs_name,0);@/
  4871. @!@:cs_name_}{\.{\\csname} primitive@>
  4872. primitive("delimiter",delim_num,0);@/
  4873. @!@:delimiter_}{\.{\\delimiter} primitive@>
  4874. primitive("divide",divide,0);@/
  4875. @!@:divide_}{\.{\\divide} primitive@>
  4876. primitive("endcsname",end_cs_name,0);@/
  4877. @!@:end_cs_name_}{\.{\\endcsname} primitive@>
  4878. primitive("endgroup",end_group,0);
  4879. @!@:end_group_}{\.{\\endgroup} primitive@>
  4880. text(frozen_end_group):="endgroup"; eqtb[frozen_end_group]:=eqtb[cur_val];@/
  4881. primitive("expandafter",expand_after,0);@/
  4882. @!@:expand_after_}{\.{\\expandafter} primitive@>
  4883. primitive("font",def_font,0);@/
  4884. @!@:font_}{\.{\\font} primitive@>
  4885. primitive("fontdimen",assign_font_dimen,0);@/
  4886. @!@:font_dimen_}{\.{\\fontdimen} primitive@>
  4887. primitive("halign",halign,0);@/
  4888. @!@:halign_}{\.{\\halign} primitive@>
  4889. primitive("hrule",hrule,0);@/
  4890. @!@:hrule_}{\.{\\hrule} primitive@>
  4891. primitive("ignorespaces",ignore_spaces,0);@/
  4892. @!@:ignore_spaces_}{\.{\\ignorespaces} primitive@>
  4893. primitive("insert",insert,0);@/
  4894. @!@:insert_}{\.{\\insert} primitive@>
  4895. primitive("mark",mark,0);@/
  4896. @!@:mark_}{\.{\\mark} primitive@>
  4897. primitive("mathaccent",math_accent,0);@/
  4898. @!@:math_accent_}{\.{\\mathaccent} primitive@>
  4899. primitive("mathchar",math_char_num,0);@/
  4900. @!@:math_char_}{\.{\\mathchar} primitive@>
  4901. primitive("mathchoice",math_choice,0);@/
  4902. @!@:math_choice_}{\.{\\mathchoice} primitive@>
  4903. primitive("multiply",multiply,0);@/
  4904. @!@:multiply_}{\.{\\multiply} primitive@>
  4905. primitive("noalign",no_align,0);@/
  4906. @!@:no_align_}{\.{\\noalign} primitive@>
  4907. primitive("noboundary",no_boundary,0);@/
  4908. @!@:no_boundary_}{\.{\\noboundary} primitive@>
  4909. primitive("noexpand",no_expand,0);@/
  4910. @!@:no_expand_}{\.{\\noexpand} primitive@>
  4911. primitive("nonscript",non_script,0);@/
  4912. @!@:non_script_}{\.{\\nonscript} primitive@>
  4913. primitive("omit",omit,0);@/
  4914. @!@:omit_}{\.{\\omit} primitive@>
  4915. primitive("parshape",set_shape,0);@/
  4916. @!@:par_shape_}{\.{\\parshape} primitive@>
  4917. primitive("penalty",break_penalty,0);@/
  4918. @!@:penalty_}{\.{\\penalty} primitive@>
  4919. primitive("prevgraf",set_prev_graf,0);@/
  4920. @!@:prev_graf_}{\.{\\prevgraf} primitive@>
  4921. primitive("radical",radical,0);@/
  4922. @!@:radical_}{\.{\\radical} primitive@>
  4923. primitive("read",read_to_cs,0);@/
  4924. @!@:read_}{\.{\\read} primitive@>
  4925. primitive("relax",relax,256); {cf.\ |scan_file_name|}
  4926. @!@:relax_}{\.{\\relax} primitive@>
  4927. text(frozen_relax):="relax"; eqtb[frozen_relax]:=eqtb[cur_val];@/
  4928. primitive("setbox",set_box,0);@/
  4929. @!@:set_box_}{\.{\\setbox} primitive@>
  4930. primitive("the",the,0);@/
  4931. @!@:the_}{\.{\\the} primitive@>
  4932. primitive("toks",toks_register,0);@/
  4933. @!@:toks_}{\.{\\toks} primitive@>
  4934. primitive("vadjust",vadjust,0);@/
  4935. @!@:vadjust_}{\.{\\vadjust} primitive@>
  4936. primitive("valign",valign,0);@/
  4937. @!@:valign_}{\.{\\valign} primitive@>
  4938. primitive("vcenter",vcenter,0);@/
  4939. @!@:vcenter_}{\.{\\vcenter} primitive@>
  4940. primitive("vrule",vrule,0);@/
  4941. @!@:vrule_}{\.{\\vrule} primitive@>
  4942. @ Each primitive has a corresponding inverse, so that it is possible to
  4943. display the cryptic numeric contents of |eqtb| in symbolic form.
  4944. Every call of |primitive| in this program is therefore accompanied by some
  4945. straightforward code that forms part of the |print_cmd_chr| routine
  4946. below.
  4947. @<Cases of |print_cmd_chr|...@>=
  4948. accent: print_esc("accent");
  4949. advance: print_esc("advance");
  4950. after_assignment: print_esc("afterassignment");
  4951. after_group: print_esc("aftergroup");
  4952. assign_font_dimen: print_esc("fontdimen");
  4953. begin_group: print_esc("begingroup");
  4954. break_penalty: print_esc("penalty");
  4955. char_num: print_esc("char");
  4956. cs_name: print_esc("csname");
  4957. def_font: print_esc("font");
  4958. delim_num: print_esc("delimiter");
  4959. divide: print_esc("divide");
  4960. end_cs_name: print_esc("endcsname");
  4961. end_group: print_esc("endgroup");
  4962. ex_space: print_esc(" ");
  4963. expand_after: print_esc("expandafter");
  4964. halign: print_esc("halign");
  4965. hrule: print_esc("hrule");
  4966. ignore_spaces: print_esc("ignorespaces");
  4967. insert: print_esc("insert");
  4968. ital_corr: print_esc("/");
  4969. mark: print_esc("mark");
  4970. math_accent: print_esc("mathaccent");
  4971. math_char_num: print_esc("mathchar");
  4972. math_choice: print_esc("mathchoice");
  4973. multiply: print_esc("multiply");
  4974. no_align: print_esc("noalign");
  4975. no_boundary:print_esc("noboundary");
  4976. no_expand: print_esc("noexpand");
  4977. non_script: print_esc("nonscript");
  4978. omit: print_esc("omit");
  4979. radical: print_esc("radical");
  4980. read_to_cs: print_esc("read");
  4981. relax: print_esc("relax");
  4982. set_box: print_esc("setbox");
  4983. set_prev_graf: print_esc("prevgraf");
  4984. set_shape: print_esc("parshape");
  4985. the: print_esc("the");
  4986. toks_register: print_esc("toks");
  4987. vadjust: print_esc("vadjust");
  4988. valign: print_esc("valign");
  4989. vcenter: print_esc("vcenter");
  4990. vrule: print_esc("vrule");
  4991. @ We will deal with the other primitives later, at some point in the program
  4992. where their |eq_type| and |equiv| values are more meaningful.  For example,
  4993. the primitives for math mode will be loaded when we consider the routines
  4994. that deal with formulas. It is easy to find where each particular
  4995. primitive was treated by looking in the index at the end; for example, the
  4996. section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
  4997. primitive'. (Primitives consisting of a single nonalphabetic character,
  4998. @!like `\.{\\/}', are listed under `Single-character primitives'.)
  4999. @!@^Single-character primitives@>
  5000. Meanwhile, this is a convenient place to catch up on something we were unable
  5001. to do before the hash table was defined:
  5002. @<Print the font identifier for |font(p)|@>=
  5003. print_esc(font_id_text(font(p)))
  5004. @* \[19] Saving and restoring equivalents.
  5005. The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
  5006. in \TeX\ means that |eqtb| entries valid in outer groups should be saved
  5007. and restored later if they are overridden inside the braces. When a new |eqtb|
  5008. value is being assigned, the program therefore checks to see if the previous
  5009. entry belongs to an outer level. In such a case, the old value is placed
  5010. on the |save_stack| just before the new value enters |eqtb|. At the
  5011. end of a grouping level, i.e., when the right brace is sensed, the
  5012. |save_stack| is used to restore the outer values, and the inner ones are
  5013. destroyed.
  5014. Entries on the |save_stack| are of type |memory_word|. The top item on
  5015. this stack is |save_stack[p]|, where |p=save_ptr-1|; it contains three
  5016. fields called |save_type|, |save_level|, and |save_index|, and it is
  5017. interpreted in one of four ways:
  5018. \yskip\hang 1) If |save_type(p)=restore_old_value|, then
  5019. |save_index(p)| is a location in |eqtb| whose current value should
  5020. be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
  5021. Furthermore if |save_index(p)>=int_base|, then |save_level(p)|
  5022. should replace the corresponding entry in |xeq_level|.
  5023. \yskip\hang 2) If |save_type(p)=restore_zero|, then |save_index(p)|
  5024. is a location in |eqtb| whose current value should be destroyed at the end
  5025. of the current group, when it should be
  5026. replaced by the current value of |eqtb[undefined_control_sequence]|.
  5027. \yskip\hang 3) If |save_type(p)=insert_token|, then |save_index(p)|
  5028. is a token that should be inserted into \TeX's input when the current
  5029. group ends.
  5030. \yskip\hang 4) If |save_type(p)=level_boundary|, then |save_level(p)|
  5031. is a code explaining what kind of group we were previously in, and
  5032. |save_index(p)| points to the level boundary word at the bottom of
  5033. the entries for that group.
  5034. @d save_type(#)==save_stack[#].hh.b0 {classifies a |save_stack| entry}
  5035. @d save_level(#)==save_stack[#].hh.b1
  5036.   {saved level for regions 5 and 6, or group code}
  5037. @d save_index(#)==save_stack[#].hh.rh
  5038.   {|eqtb| location or |save_stack| location}
  5039. @d restore_old_value=0 {|save_type| when a value should be restored later}
  5040. @d restore_zero=1 {|save_type| when an undefined entry should be restored}
  5041. @d insert_token=2 {|save_type| when a token is being saved for later use}
  5042. @d level_boundary=3 {|save_type| corresponding to beginning of group}
  5043. @ Here are the group codes that are used to discriminate between different
  5044. kinds of groups. They allow \TeX\ to decide what special actions, if any,
  5045. should be performed when a group ends.
  5046. \def\grp{\.{\char'173...\char'175}}
  5047. Some groups are not supposed to be ended by right braces. For example,
  5048. the `\.\$' that begins a math formula causes a |math_shift_group| to
  5049. be started, and this should be terminated by a matching `\.\$'. Similarly,
  5050. a group that starts with \.{\\left} should end with \.{\\right}, and
  5051. one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
  5052. @d bottom_level=0 {group code for the outside world}
  5053. @d simple_group=1 {group code for local structure only}
  5054. @d hbox_group=2 {code for `\.{\\hbox}\grp'}
  5055. @d adjusted_hbox_group=3 {code for `\.{\\hbox}\grp' in vertical mode}
  5056. @d vbox_group=4 {code for `\.{\\vbox}\grp'}
  5057. @d vtop_group=5 {code for `\.{\\vtop}\grp'}
  5058. @d align_group=6 {code for `\.{\\halign}\grp', `\.{\\valign}\grp'}
  5059. @d no_align_group=7 {code for `\.{\\noalign}\grp'}
  5060. @d output_group=8 {code for output routine}
  5061. @d math_group=9 {code for, e.g, `\.{\char'136}\grp'}
  5062. @d disc_group=10 {code for `\.{\\discretionary}\grp\grp\grp'}
  5063. @d insert_group=11 {code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'}
  5064. @d vcenter_group=12 {code for `\.{\\vcenter}\grp'}
  5065. @d math_choice_group=13 {code for `\.{\\mathchoice}\grp\grp\grp\grp'}
  5066. @d semi_simple_group=14 {code for `\.{\\begingroup...\\endgroup}'}
  5067. @d math_shift_group=15 {code for `\.{\$...\$}'}
  5068. @d math_left_group=16 {code for `\.{\\left...\\right}'}
  5069. @d max_group_code=16
  5070. @<Types...@>=
  5071. @!group_code=0..max_group_code; {|save_level| for a level boundary}
  5072. @ The global variable |cur_group| keeps track of what sort of group we are
  5073. currently in. Another global variable, |cur_boundary|, points to the
  5074. topmost |level_boundary| word.  And |cur_level| is the current depth of
  5075. nesting. The routines are designed to preserve the condition that no entry
  5076. in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
  5077. @ @<Glob...@>=
  5078. @!save_stack : array[0..save_size] of memory_word;
  5079. @!save_ptr : 0..save_size; {first unused entry on |save_stack|}
  5080. @!max_save_stack:0..save_size; {maximum usage of save stack}
  5081. @!cur_level: quarterword; {current nesting level for groups}
  5082. @!cur_group: group_code; {current group type}
  5083. @!cur_boundary: 0..save_size; {where the current level begins}
  5084. @ At this time it might be a good idea for the reader to review the introduction
  5085. to |eqtb| that was given above just before the long lists of parameter names.
  5086. Recall that the ``outer level'' of the program is |level_one|, since
  5087. undefined control sequences are assumed to be ``defined'' at |level_zero|.
  5088. @<Set init...@>=
  5089. save_ptr:=0; cur_level:=level_one; cur_group:=bottom_level; cur_boundary:=0;
  5090. max_save_stack:=0;
  5091. @ The following macro is used to test if there is room for up to six more
  5092. entries on |save_stack|. By making a conservative test like this, we can
  5093. get by with testing for overflow in only a few places.
  5094. @d check_full_save_stack==if save_ptr>max_save_stack then
  5095.   begin max_save_stack:=save_ptr;
  5096.   if max_save_stack>save_size-6 then overflow("save size",save_size);
  5097. @:TeX capacity exceeded save size}{\quad save size@>
  5098.   end
  5099. @ Procedure |new_save_level| is called when a group begins. The
  5100. argument is a group identification code like `|hbox_group|'. After
  5101. calling this routine, it is safe to put five more entries on |save_stack|.
  5102. In some cases integer-valued items are placed onto the
  5103. |save_stack| just below a |level_boundary| word, because this is a
  5104. convenient place to keep information that is supposed to ``pop up'' just
  5105. when the group has finished.
  5106. For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
  5107. dimension is stored on |save_stack| just before |new_save_level| is
  5108. called.
  5109. We use the notation |saved(k)| to stand for an integer item that
  5110. appears in location |save_ptr+k| of the save stack.
  5111. @d saved(#)==save_stack[save_ptr+#].int
  5112. @p procedure new_save_level(@!c:group_code); {begin a new level of grouping}
  5113. begin check_full_save_stack;
  5114. save_type(save_ptr):=level_boundary; save_level(save_ptr):=cur_group;
  5115. save_index(save_ptr):=cur_boundary;
  5116. if cur_level=max_quarterword then overflow("grouping levels",
  5117. @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
  5118.   max_quarterword-min_quarterword);
  5119.   {quit if |(cur_level+1)| is too big to be stored in |eqtb|}
  5120. cur_boundary:=save_ptr; incr(cur_level); incr(save_ptr); cur_group:=c;
  5121. @ Just before an entry of |eqtb| is changed, the following procedure should
  5122. be called to update the other data structures properly. It is important
  5123. to keep in mind that reference counts in |mem| include references from
  5124. within |save_stack|, so these counts must be handled carefully.
  5125. @^reference counts@>
  5126. @p procedure eq_destroy(@!w:memory_word); {gets ready to forget |w|}
  5127. var q:pointer; {|equiv| field of |w|}
  5128. begin case eq_type_field(w) of
  5129. call,long_call,outer_call,long_outer_call: delete_token_ref(equiv_field(w));
  5130. glue_ref: delete_glue_ref(equiv_field(w));
  5131. shape_ref: begin q:=equiv_field(w); {we need to free a \.{\\parshape} block}
  5132.   if q<>null then free_node(q,info(q)+info(q)+1);
  5133.   end; {such a block is |2n+1| words long, where |n=info(q)|}
  5134. box_ref: flush_node_list(equiv_field(w));
  5135. othercases do_nothing
  5136. endcases;
  5137. @ To save a value of |eqtb[p]| that was established at level |l|, we
  5138. can use the following subroutine.
  5139. @p procedure eq_save(@!p:pointer;@!l:quarterword); {saves |eqtb[p]|}
  5140. begin check_full_save_stack;
  5141. if l=level_zero then save_type(save_ptr):=restore_zero
  5142. else  begin save_stack[save_ptr]:=eqtb[p]; incr(save_ptr);
  5143.   save_type(save_ptr):=restore_old_value;
  5144.   end;
  5145. save_level(save_ptr):=l; save_index(save_ptr):=p; incr(save_ptr);
  5146. @ The procedure |eq_define| defines an |eqtb| entry having specified
  5147. |eq_type| and |equiv| fields, and saves the former value if appropriate.
  5148. This procedure is used only for entries in the first four regions of |eqtb|,
  5149. i.e., only for entries that have |eq_type| and |equiv| fields.
  5150. After calling this routine, it is safe to put four more entries on
  5151. |save_stack|, provided that there was room for four more entries before
  5152. the call, since |eq_save| makes the necessary test.
  5153. @p procedure eq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
  5154.   {new data for |eqtb|}
  5155. begin if eq_level(p)=cur_level then eq_destroy(eqtb[p])
  5156. else if cur_level>level_one then eq_save(p,eq_level(p));
  5157. eq_level(p):=cur_level; eq_type(p):=t; equiv(p):=e;
  5158. @ The counterpart of |eq_define| for the remaining (fullword) positions in
  5159. |eqtb| is called |eq_word_define|. Since |xeq_level[p]>=level_one| for all
  5160. |p|, a `|restore_zero|' will never be used in this case.
  5161. @p procedure eq_word_define(@!p:pointer;@!w:integer);
  5162. begin if xeq_level[p]<>cur_level then
  5163.   begin eq_save(p,xeq_level[p]); xeq_level[p]:=cur_level;
  5164.   end;
  5165. eqtb[p].int:=w;
  5166. @ The |eq_define| and |eq_word_define| routines take care of local definitions.
  5167. @^global definitions@>
  5168. Global definitions are done in almost the same way, but there is no need
  5169. to save old values, and the new value is associated with |level_one|.
  5170. @p procedure geq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
  5171.   {global |eq_define|}
  5172. begin eq_destroy(eqtb[p]);
  5173. eq_level(p):=level_one; eq_type(p):=t; equiv(p):=e;
  5174. procedure geq_word_define(@!p:pointer;@!w:integer); {global |eq_word_define|}
  5175. begin eqtb[p].int:=w; xeq_level[p]:=level_one;
  5176. @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
  5177. @p procedure save_for_after(@!t:halfword);
  5178. begin if cur_level>level_one then
  5179.   begin check_full_save_stack;
  5180.   save_type(save_ptr):=insert_token; save_level(save_ptr):=level_zero;
  5181.   save_index(save_ptr):=t; incr(save_ptr);
  5182.   end;
  5183. @ The |unsave| routine goes the other way, taking items off of |save_stack|.
  5184. This routine takes care of restoration when a level ends; everything
  5185. belonging to the topmost group is cleared off of the save stack.
  5186. @p@t\4@>@<Declare the procedure called |restore_trace|@>@;@/
  5187. procedure@?back_input; forward; @t\2@>
  5188. procedure unsave; {pops the top level off the save stack}
  5189. label done;
  5190. var p:pointer; {position to be restored}
  5191. @!l:quarterword; {saved level, if in fullword regions of |eqtb|}
  5192. @!t:halfword; {saved value of |cur_tok|}
  5193. begin if cur_level>level_one then
  5194.   begin decr(cur_level);
  5195.   @<Clear off top level from |save_stack|@>;
  5196.   end
  5197. else confusion("curlevel"); {|unsave| is not used when |cur_group=bottom_level|}
  5198. @:this can't happen curlevel}{\quad curlevel@>
  5199. @ @<Clear off...@>=
  5200. loop@+begin decr(save_ptr);
  5201.   if save_type(save_ptr)=level_boundary then goto done;
  5202.   p:=save_index(save_ptr);
  5203.   if save_type(save_ptr)=insert_token then
  5204.     @<Insert token |p| into \TeX's input@>
  5205.   else  begin if save_type(save_ptr)=restore_old_value then
  5206.       begin l:=save_level(save_ptr); decr(save_ptr);
  5207.       end
  5208.     else save_stack[save_ptr]:=eqtb[undefined_control_sequence];
  5209.     @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless
  5210.       |eqtb[p]| holds a global value@>;
  5211.     end;
  5212.   end;
  5213. done: cur_group:=save_level(save_ptr); cur_boundary:=save_index(save_ptr)
  5214. @ A global definition, which sets the level to |level_one|,
  5215. @^global definitions@>
  5216. will not be undone by |unsave|. If at least one global definition of
  5217. |eqtb[p]| has been carried out within the group that just ended, the
  5218. last such definition will therefore survive.
  5219. @<Store \(s)|save...@>=
  5220. if p<int_base then
  5221.   if eq_level(p)=level_one then
  5222.     begin eq_destroy(save_stack[save_ptr]); {destroy the saved value}
  5223.     @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
  5224.     end
  5225.   else  begin eq_destroy(eqtb[p]); {destroy the current value}
  5226.     eqtb[p]:=save_stack[save_ptr]; {restore the saved value}
  5227.     @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
  5228.     end
  5229. else if xeq_level[p]<>level_one then
  5230.   begin eqtb[p]:=save_stack[save_ptr]; xeq_level[p]:=l;
  5231.   @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
  5232.   end
  5233. else  begin
  5234.   @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
  5235.   end
  5236. @ @<Declare the procedure called |restore_trace|@>=
  5237. @!stat procedure restore_trace(@!p:pointer;@!s:str_number);
  5238.   {|eqtb[p]| has just been restored or retained}
  5239. begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
  5240. show_eqtb(p); print_char("}");
  5241. end_diagnostic(false);
  5242. @ When looking for possible pointers to a memory location, it is helpful
  5243. to look for references from |eqtb| that might be waiting on the
  5244. save stack. Of course, we might find spurious pointers too; but this
  5245. routine is merely an aid when debugging, and at such times we are
  5246. grateful for any scraps of information, even if they prove to be irrelevant.
  5247. @^dirty \PASCAL@>
  5248. @<Search |save_stack| for equivalents that point to |p|@>=
  5249. if save_ptr>0 then for q:=0 to save_ptr-1 do
  5250.   begin if equiv_field(save_stack[q])=p then
  5251.     begin print_nl("SAVE("); print_int(q); print_char(")");
  5252.     end;
  5253.   end
  5254. @ Most of the parameters kept in |eqtb| can be changed freely, but there's
  5255. an exception:  The magnification should not be used with two different
  5256. values during any \TeX\ job, since a single magnification is applied to an
  5257. entire run. The global variable |mag_set| is set to the current magnification
  5258. whenever it becomes necessary to ``freeze'' it at a particular value.
  5259. @<Glob...@>=
  5260. @!mag_set:integer; {if nonzero, this magnification should be used henceforth}
  5261. @ @<Set init...@>=
  5262. mag_set:=0;
  5263. @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
  5264. for magnification.
  5265. @p procedure prepare_mag;
  5266. begin if (mag_set>0)and(mag<>mag_set) then
  5267.   begin print_err("Incompatible magnification ("); print_int(mag);
  5268. @.Incompatible magnification@>
  5269.   print(");"); print_nl(" the previous value will be retained");
  5270.   help2("I can handle only one magnification ratio per job. So I've")@/
  5271.   ("reverted to the magnification you used earlier on this run.");@/
  5272.   int_error(mag_set);
  5273.   geq_word_define(int_base+mag_code,mag_set); {|mag:=mag_set|}
  5274.   end;
  5275. if (mag<=0)or(mag>32768) then
  5276.   begin print_err("Illegal magnification has been changed to 1000");@/
  5277. @.Illegal magnification...@>
  5278.   help1("The magnification ratio must be between 1 and 32768.");
  5279.   int_error(mag); geq_word_define(int_base+mag_code,1000);
  5280.   end;
  5281. mag_set:=mag;
  5282. @* \[20] Token lists.
  5283. A \TeX\ token is either a character or a control sequence, and it is
  5284. @^token@>
  5285. represented internally in one of two ways: (1)~A character whose ASCII
  5286. code number is |c| and whose command code is |m| is represented as the
  5287. number $2^8m+c$; the command code is in the range |1<=m<=14|. (2)~A control
  5288. sequence whose |eqtb| address is |p| is represented as the number
  5289. |cs_token_flag+p|. Here |cs_token_flag=@t$2^{12}-1$@>| is larger than
  5290. $2^8m+c$, yet it is small enough that |cs_token_flag+p< max_halfword|;
  5291. thus, a token fits comfortably in a halfword.
  5292. A token |t| represents a |left_brace| command if and only if
  5293. |t<left_brace_limit|; it represents a |right_brace| command if and only if
  5294. we have |left_brace_limit<=t<right_brace_limit|; and it represents a |match| or
  5295. |end_match| command if and only if |match_token<=t<=end_match_token|.
  5296. The following definitions take care of these token-oriented constants
  5297. and a few others.
  5298. @d cs_token_flag==@'7777 {amount added to the |eqtb| location in a
  5299.   token that stands for a control sequence; is a multiple of~256, less~1}
  5300. @d left_brace_token=@'0400 {$2^8\cdot|left_brace|$}
  5301. @d left_brace_limit=@'1000 {$2^8\cdot(|left_brace|+1)$}
  5302. @d right_brace_token=@'1000 {$2^8\cdot|right_brace|$}
  5303. @d right_brace_limit=@'1400 {$2^8\cdot(|right_brace|+1)$}
  5304. @d math_shift_token=@'1400 {$2^8\cdot|math_shift|$}
  5305. @d tab_token=@'2000 {$2^8\cdot|tab_mark|$}
  5306. @d out_param_token=@'2400 {$2^8\cdot|out_param|$}
  5307. @d space_token=@'5040 {$2^8\cdot|spacer|+|" "|$}
  5308. @d letter_token=@'5400 {$2^8\cdot|letter|$}
  5309. @d other_token=@'6000 {$2^8\cdot|other_char|$}
  5310. @d match_token=@'6400 {$2^8\cdot|match|$}
  5311. @d end_match_token=@'7000 {$2^8\cdot|end_match|$}
  5312. @ @<Check the ``constant''...@>=
  5313. if cs_token_flag+undefined_control_sequence>max_halfword then bad:=21;
  5314. @ A token list is a singly linked list of one-word nodes in |mem|, where
  5315. each word contains a token and a link. Macro definitions, output-routine
  5316. definitions, marks, \.{\\write} texts, and a few other things
  5317. are remembered by \TeX\ in the form
  5318. of token lists, usually preceded by a node with a reference count in its
  5319. |token_ref_count| field. The token stored in location |p| is called
  5320. |info(p)|.
  5321. Three special commands appear in the token lists of macro definitions.
  5322. When |m=match|, it means that \TeX\ should scan a parameter
  5323. for the current macro; when |m=end_match|, it means that parameter
  5324. matching should end and \TeX\ should start reading the macro text; and
  5325. when |m=out_param|, it means that \TeX\ should insert parameter
  5326. number |c| into the text at this point.
  5327. The enclosing \.{\char'173} and \.{\char'175} characters of a macro
  5328. definition are omitted, but the final right brace of an output routine
  5329. is included at the end of its token list.
  5330. Here is an example macro definition that illustrates these conventions.
  5331. After \TeX\ processes the text
  5332. $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
  5333. the definition of \.{\\mac} is represented as a token list containing
  5334. $$\def\,{\hskip2pt}
  5335. \vbox{\halign{\hfil#\hfil\cr
  5336. (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
  5337. \.{\\b}, |end_match|,\cr
  5338. |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
  5339. |other_char|\,\.1,\cr
  5340. |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
  5341. The procedure |scan_toks| builds such token lists, and |macro_call|
  5342. does the parameter matching.
  5343. @^reference counts@>
  5344. Examples such as
  5345. $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
  5346. explain why reference counts would be needed even if \TeX\ had no \.{\\let}
  5347. operation: When the token list for \.{\\m} is being read, the redefinition of
  5348. \.{\\m} changes the |eqtb| entry before the token list has been fully
  5349. consumed, so we dare not simply destroy a token list when its
  5350. control sequence is being redefined.
  5351. If the parameter-matching part of a definition ends with `\.{\#\{}',
  5352. the corresponding token list will have `\.\{' just before the `|end_match|'
  5353. and also at the very end. The first `\.\{' is used to delimit the parameter; the
  5354. second one keeps the first from disappearing.
  5355. @ The procedure |show_token_list|, which prints a symbolic form of
  5356. the token list that starts at a given node |p|, illustrates these
  5357. conventions. The token list being displayed should not begin with a reference
  5358. count. However, the procedure is intended to be robust, so that if the
  5359. memory links are awry or if |p| is not really a pointer to a token list,
  5360. nothing catastrophic will happen.
  5361. An additional parameter |q| is also given; this parameter is either null
  5362. or it points to a node in the token list where a certain magic computation
  5363. takes place that will be explained later. (Basically, |q| is non-null when
  5364. we are printing the two-line context information at the time of an error
  5365. message; |q| marks the place corresponding to where the second line
  5366. should begin.)
  5367. For example, if |p| points to the node containing the first \.a in the
  5368. token list above, then |show_token_list| will print the string
  5369. $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
  5370. and if |q| points to the node containing the second \.a,
  5371. the magic computation will be performed just before the second \.a is printed.
  5372. The generation will stop, and `\.{\\ETC.}' will be printed, if the length
  5373. of printing exceeds a given limit~|l|. Anomalous entries are printed in the
  5374. form of control sequences that are not followed by a blank space, e.g.,
  5375. `\.{\\BAD.}'; this cannot be confused with actual control sequences because
  5376. a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
  5377. @<Declare the procedure called |show_token_list|@>=
  5378. procedure show_token_list(@!p,@!q:integer;@!l:integer);
  5379. label exit;
  5380. var m,@!c:integer; {pieces of a token}
  5381. @!match_chr:ASCII_code; {character used in a `|match|'}
  5382. @!n:ASCII_code; {the highest parameter number, as an ASCII digit}
  5383. begin match_chr:="#"; n:="0"; tally:=0;
  5384. while (p<>null) and (tally<l) do
  5385.   begin if p=q then @<Do magic computation@>;
  5386.   @<Display token |p|, and |return| if there are problems@>;
  5387.   p:=link(p);
  5388.   end;
  5389. if p<>null then print_esc("ETC.");
  5390. @.ETC@>
  5391. exit:
  5392. @ @<Display token |p|...@>=
  5393. if (p<hi_mem_min) or (p>mem_end) then
  5394.   begin print_esc("CLOBBERED."); return;
  5395. @.CLOBBERED@>
  5396.   end;
  5397. if info(p)>=cs_token_flag then print_cs(info(p)-cs_token_flag)
  5398. else  begin m:=info(p) div @'400; c:=info(p) mod @'400;
  5399.   if info(p)<0 then print_esc("BAD.")
  5400. @.BAD@>
  5401.   else @<Display the token $(|m|,|c|)$@>;
  5402.   end
  5403. @ The procedure usually ``learns'' the character code used for macro
  5404. parameters by seeing one in a |match| command before it runs into any
  5405. |out_param| commands.
  5406. @<Display the token ...@>=
  5407. case m of
  5408. left_brace,right_brace,math_shift,tab_mark,sup_mark,sub_mark,spacer,
  5409.   letter,other_char: print(c);
  5410. mac_param: begin print(c); print(c);
  5411.   end;
  5412. out_param: begin print(match_chr);
  5413.   if c<=9 then print_char(c+"0")
  5414.   else  begin print_char("!"); return;
  5415.     end;
  5416.   end;
  5417. match: begin match_chr:=c; print(c); incr(n); print_char(n);
  5418.   if n>"9" then return;
  5419.   end;
  5420. end_match: print("->");
  5421. @.->@>
  5422. othercases print_esc("BAD.")
  5423. @.BAD@>
  5424. endcases
  5425. @ Here's the way we sometimes want to display a token list, given a pointer
  5426. to its reference count; the pointer may be null.
  5427. @p procedure token_show(@!p:pointer);
  5428. begin if p<>null then show_token_list(link(p),null,10000000);
  5429. @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
  5430. symbolic form, including the expansion of a macro or mark.
  5431. @p procedure print_meaning;
  5432. begin print_cmd_chr(cur_cmd,cur_chr);
  5433. if cur_cmd>=call then
  5434.   begin print_char(":"); print_ln; token_show(cur_chr);
  5435.   end
  5436. else if cur_cmd=top_bot_mark then
  5437.   begin print_char(":"); print_ln;
  5438.   token_show(cur_mark[cur_chr]);
  5439.   end;
  5440. @* \[21] Introduction to the syntactic routines.
  5441. Let's pause a moment now and try to look at the Big Picture.
  5442. The \TeX\ program consists of three main parts: syntactic routines,
  5443. semantic routines, and output routines. The chief purpose of the
  5444. syntactic routines is to deliver the user's input to the semantic routines,
  5445. one token at a time. The semantic routines act as an interpreter
  5446. responding to these tokens, which may be regarded as commands. And the
  5447. output routines are periodically called on to convert box-and-glue
  5448. lists into a compact set of instructions that will be sent
  5449. to a typesetter. We have discussed the basic data structures and utility
  5450. routines of \TeX, so we are good and ready to plunge into the real activity by
  5451. considering the syntactic routines.
  5452. Our current goal is to come to grips with the |get_next| procedure,
  5453. which is the keystone of \TeX's input mechanism. Each call of |get_next|
  5454. sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
  5455. representing the next input token.
  5456. $$\vbox{\halign{#\hfil\cr
  5457.   \hbox{|cur_cmd| denotes a command code from the long list of codes
  5458.    given above;}\cr
  5459.   \hbox{|cur_chr| denotes a character code or other modifier of the command
  5460.    code;}\cr
  5461.   \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
  5462.   \hbox{\qquad if the current token was a control sequence,
  5463.    otherwise it's zero.}\cr}}$$
  5464. Underlying this external behavior of |get_next| is all the machinery
  5465. necessary to convert from character files to tokens. At a given time we
  5466. may be only partially finished with the reading of several files (for
  5467. which \.{\\input} was specified), and partially finished with the expansion
  5468. of some user-defined macros and/or some macro parameters, and partially
  5469. finished with the generation of some text in a template for \.{\\halign},
  5470. and so on. When reading a character file, special characters must be
  5471. classified as math delimiters, etc.; comments and extra blank spaces must
  5472. be removed, paragraphs must be recognized, and control sequences must be
  5473. found in the hash table. Furthermore there are occasions in which the
  5474. scanning routines have looked ahead for a word like `\.{plus}' but only
  5475. part of that word was found, hence a few characters must be put back
  5476. into the input and scanned again.
  5477. To handle these situations, which might all be present simultaneously,
  5478. \TeX\ uses various stacks that hold information about the incomplete
  5479. activities, and there is a finite state control for each level of the
  5480. input mechanism. These stacks record the current state of an implicitly
  5481. recursive process, but the |get_next| procedure is not recursive.
  5482. Therefore it will not be difficult to translate these algorithms into
  5483. low-level languages that do not support recursion.
  5484. @<Glob...@>=
  5485. @!cur_cmd: eight_bits; {current command set by |get_next|}
  5486. @!cur_chr: halfword; {operand of current command}
  5487. @!cur_cs: pointer; {control sequence found here, zero if none found}
  5488. @!cur_tok: halfword; {packed representative of |cur_cmd| and |cur_chr|}
  5489. @ The |print_cmd_chr| routine prints a symbolic interpretation of a
  5490. command code and its modifier. This is used in certain `\.{You can\'t}'
  5491. error messages, and in the implementation of diagnostic routines like
  5492. \.{\\show}.
  5493. The body of |print_cmd_chr| is a rather tedious listing of print
  5494. commands, and most of it is essentially an inverse to the |primitive|
  5495. routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
  5496. this procedure appears elsewhere in the program,
  5497. together with the corresponding |primitive| calls.
  5498. @d chr_cmd(#)==begin print(#); print_ASCII(chr_code);
  5499.   end
  5500. @<Declare the procedure called |print_cmd_chr|@>=
  5501. procedure print_cmd_chr(@!cmd:quarterword;@!chr_code:halfword);
  5502. begin case cmd of
  5503. left_brace: chr_cmd("begin-group character ");
  5504. right_brace: chr_cmd("end-group character ");
  5505. math_shift: chr_cmd("math shift character ");
  5506. mac_param: chr_cmd("macro parameter character ");
  5507. sup_mark: chr_cmd("superscript character ");
  5508. sub_mark: chr_cmd("subscript character ");
  5509. endv: print("end of alignment template");
  5510. spacer: chr_cmd("blank space ");
  5511. letter: chr_cmd("the letter ");
  5512. other_char: chr_cmd("the character ");
  5513. @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
  5514. othercases print("[unknown command code!]")
  5515. endcases;
  5516. @ Here is a procedure that displays the current command.
  5517. @p procedure show_cur_cmd_chr;
  5518. begin begin_diagnostic; print_nl("{");
  5519. if mode<>shown_mode then
  5520.   begin print_mode(mode); print(": "); shown_mode:=mode;
  5521.   end;
  5522. print_cmd_chr(cur_cmd,cur_chr); print_char("}");
  5523. end_diagnostic(false);
  5524. @* \[22] Input stacks and states.
  5525. This implementation of
  5526. \TeX\ uses two different conventions for representing sequential stacks.
  5527. @^stack conventions@>@^conventions for representing stacks@>
  5528. \yskip\hang 1) If there is frequent access to the top entry, and if the
  5529. stack is essentially never empty, then the top entry is kept in a global
  5530. variable (even better would be a machine register), and the other entries
  5531. appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
  5532. semantic stack described above is handled this way, and so is the input
  5533. stack that we are about to study.
  5534. \yskip\hang 2) If there is infrequent top access, the entire stack contents
  5535. are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
  5536. is treated this way, as we have seen.
  5537. \yskip\noindent
  5538. The state of \TeX's input mechanism appears in the input stack, whose
  5539. entries are records with six fields, called |state|, |index|, |start|, |loc|,
  5540. |limit|, and |name|. This stack is maintained with
  5541. convention~(1), so it is declared in the following way:
  5542. @<Types...@>=
  5543. @!in_state_record = record
  5544.   @!state_field, @!index_field: quarterword;
  5545.   @!start_field,@!loc_field, @!limit_field, @!name_field: halfword;
  5546.   end;
  5547. @ @<Glob...@>=
  5548. @!input_stack : array[0..stack_size] of in_state_record;
  5549. @!input_ptr : 0..stack_size; {first unused location of |input_stack|}
  5550. @!max_in_stack: 0..stack_size; {largest value of |input_ptr| when pushing}
  5551. @!cur_input : in_state_record;
  5552.   {the ``top'' input state, according to convention (1)}
  5553. @ We've already defined the special variable |loc==cur_input.loc_field|
  5554. in our discussion of basic input-output routines. The other components of
  5555. |cur_input| are defined in the same way:
  5556. @d state==cur_input.state_field {current scanner state}
  5557. @d index==cur_input.index_field {reference for buffer information}
  5558. @d start==cur_input.start_field {starting position in |buffer|}
  5559. @d limit==cur_input.limit_field {end of current line in |buffer|}
  5560. @d name==cur_input.name_field {name of the current file}
  5561. @ Let's look more closely now at the control variables
  5562. (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
  5563. assuming that \TeX\ is reading a line of characters that have been input
  5564. from some file or from the user's terminal. There is an array called
  5565. |buffer| that acts as a stack of all lines of characters that are
  5566. currently being read from files, including all lines on subsidiary
  5567. levels of the input stack that are not yet completed. \TeX\ will return to
  5568. the other lines when it is finished with the present input file.
  5569. (Incidentally, on a machine with byte-oriented addressing, it might be
  5570. appropriate to combine |buffer| with the |str_pool| array,
  5571. letting the buffer entries grow downward from the top of the string pool
  5572. and checking that these two tables don't bump into each other.)
  5573. The line we are currently working on begins in position |start| of the
  5574. buffer; the next character we are about to read is |buffer[loc]|; and
  5575. |limit| is the location of the last character present.  If |loc>limit|,
  5576. the line has been completely read. Usually |buffer[limit]| is the
  5577. |end_line_char|, denoting the end of a line, but this is not
  5578. true if the current line is an insertion that was entered on the user's
  5579. terminal in response to an error message.
  5580. The |name| variable is a string number that designates the name of
  5581. the current file, if we are reading a text file. It is zero if we
  5582. are reading from the terminal; it is |n+1| if we are reading from
  5583. input stream |n|, where |0<=n<=16|. (Input stream 16 stands for
  5584. an invalid stream number; in such cases the input is actually from
  5585. the terminal, under control of the procedure |read_toks|.)
  5586. The |state| variable has one of three values, when we are scanning such
  5587. files:
  5588. $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
  5589. 1) |state=mid_line| is the normal state.\cr
  5590. 2) |state=skip_blanks| is like |mid_line|, but blanks are ignored.\cr
  5591. 3) |state=new_line| is the state at the beginning of a line.\cr}}$$
  5592. These state values are assigned numeric codes so that if we add the state
  5593. code to the next character's command code, we get distinct values. For
  5594. example, `|mid_line+spacer|' stands for the case that a blank
  5595. space character occurs in the middle of a line when it is not being
  5596. ignored; after this case is processed, the next value of |state| will
  5597. be |skip_blanks|.
  5598. @d mid_line=1 {|state| code when scanning a line of characters}
  5599. @d skip_blanks=2+max_char_code {|state| code when ignoring blanks}
  5600. @d new_line=3+max_char_code+max_char_code {|state| code at start of line}
  5601. @ Additional information about the current line is available via the
  5602. |index| variable, which counts how many lines of characters are present
  5603. in the buffer below the current level. We have |index=0| when reading
  5604. from the terminal and prompting the user for each line; then if the user types,
  5605. e.g., `\.{\\input paper}', we will have |index=1| while reading
  5606. the file \.{paper.tex}. However, it does not follow that |index| is the
  5607. same as the input stack pointer, since many of the levels on the input
  5608. stack may come from token lists. For example, the instruction `\.{\\input
  5609. paper}' might occur in a token list.
  5610. The global variable |in_open| is equal to the |index|
  5611. value of the highest non-token-list level. Thus, the number of partially read
  5612. lines in the buffer is |in_open+1|, and we have |in_open=index|
  5613. when we are not reading a token list.
  5614. If we are not currently reading from the terminal, or from an input
  5615. stream, we are reading from the file variable |input_file[index]|. We use
  5616. the notation |terminal_input| as a convenient abbreviation for |name=0|,
  5617. and |cur_file| as an abbreviation for |input_file[index]|.
  5618. The global variable |line| contains the line number in the topmost
  5619. open file, for use in error messages. If we are not reading from
  5620. the terminal, |line_stack[index]| holds the line number for the
  5621. enclosing level, so that |line| can be restored when the current
  5622. file has been read. Line numbers should never be negative, since the
  5623. negative of the current line number is used to identify the user's output
  5624. routine in the |mode_line| field of the semantic nest entries.
  5625. If more information about the input state is needed, it can be
  5626. included in small arrays like those shown here. For example,
  5627. the current page or segment number in the input file might be
  5628. put into a variable |@!page|, maintained for enclosing levels in
  5629. `\ignorespaces|@!page_stack:array[1..max_in_open] of integer|\unskip'
  5630. by analogy with |line_stack|.
  5631. @^system dependencies@>
  5632. @d terminal_input==(name=0) {are we reading from the terminal?}
  5633. @d cur_file==input_file[index] {the current |alpha_file| variable}
  5634. @<Glob...@>=
  5635. @!in_open : 0..max_in_open; {the number of lines in the buffer, less one}
  5636. @!open_parens : 0..max_in_open; {the number of open text files}
  5637. @!input_file : array[1..max_in_open] of alpha_file;
  5638. @!line : integer; {current line number in the current source file}
  5639. @!line_stack : array[1..max_in_open] of integer;
  5640. @ Users of \TeX\ sometimes forget to balance left and right braces properly,
  5641. and one of the ways \TeX\ tries to spot such errors is by considering an
  5642. input file as broken into subfiles by control sequences that
  5643. are declared to be \.{\\outer}.
  5644. A variable called |scanner_status| tells \TeX\ whether or not to complain
  5645. when a subfile ends. This variable has six possible values:
  5646. \yskip\hang|normal|, means that a subfile can safely end here without incident.
  5647. \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
  5648. because we're reading past some conditional text that was not selected.
  5649. \yskip\hang|defining|, means that a subfile shouldn't end now because a
  5650. macro is being defined.
  5651. \yskip\hang|matching|, means that a subfile shouldn't end now because a
  5652. macro is being used and we are searching for the end of its arguments.
  5653. \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
  5654. not finished with the preamble of an \.{\\halign} or \.{\\valign}.
  5655. \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
  5656. reading a balanced token list for \.{\\message}, \.{\\write}, etc.
  5657. \yskip\noindent
  5658. If the |scanner_status| is not |normal|, the variable |warning_index| points
  5659. to the |eqtb| location for the relevant control sequence name to print
  5660. in an error message.
  5661. @d skipping=1 {|scanner_status| when passing conditional text}
  5662. @d defining=2 {|scanner_status| when reading a macro definition}
  5663. @d matching=3 {|scanner_status| when reading macro arguments}
  5664. @d aligning=4 {|scanner_status| when reading an alignment preamble}
  5665. @d absorbing=5 {|scanner_status| when reading a balanced text}
  5666. @<Glob...@>=
  5667. @!scanner_status : normal..absorbing; {can a subfile end now?}
  5668. @!warning_index : pointer; {identifier relevant to non-|normal| scanner status}
  5669. @!def_ref : pointer; {reference count of token list being defined}
  5670. @ Here is a procedure that uses |scanner_status| to print a warning message
  5671. when a subfile has ended, and at certain other crucial times:
  5672. @<Declare the procedure called |runaway|@>=
  5673. procedure runaway;
  5674. var p:pointer; {head of runaway list}
  5675. begin if scanner_status>skipping then
  5676.   begin print_nl("Runaway ");
  5677. @.Runaway...@>
  5678.   case scanner_status of
  5679.   defining: begin print("definition"); p:=def_ref;
  5680.     end;
  5681.   matching: begin print("argument"); p:=temp_head;
  5682.     end;
  5683.   aligning: begin print("preamble"); p:=hold_head;
  5684.     end;
  5685.   absorbing: begin print("text"); p:=def_ref;
  5686.     end;
  5687.   end; {there are no other cases}
  5688.   print_char("?");print_ln; show_token_list(link(p),null,error_line-10);
  5689.   end;
  5690. @ However, all this discussion about input state really applies only to the
  5691. case that we are inputting from a file. There is another important case,
  5692. namely when we are currently getting input from a token list. In this case
  5693. |state=token_list|, and the conventions about the other state variables
  5694. are different:
  5695. \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
  5696. the node that will be read next. If |loc=null|, the token list has been
  5697. fully read.
  5698. \yskip\hang|start| points to the first node of the token list; this node
  5699. may or may not contain a reference count, depending on the type of token
  5700. list involved.
  5701. \yskip\hang|token_type|, which takes the place of |index| in the
  5702. discussion above, is a code number that explains what kind of token list
  5703. is being scanned.
  5704. \yskip\hang|name| points to the |eqtb| address of the control sequence
  5705. being expanded, if the current token list is a macro.
  5706. \yskip\hang|param_start|, which takes the place of |limit|, tells where
  5707. the parameters of the current macro begin in the |param_stack|, if the
  5708. current token list is a macro.
  5709. \yskip\noindent The |token_type| can take several values, depending on
  5710. where the current token list came from:
  5711. \yskip\hang|parameter|, if a parameter is being scanned;
  5712. \hang|u_template|, if the \<u_j> part of an alignment
  5713. template is being scanned;
  5714. \hang|v_template|, if the \<v_j> part of an alignment
  5715. template is being scanned;
  5716. \hang|backed_up|, if the token list being scanned has been inserted as
  5717. `to be read again'.
  5718. \hang|inserted|, if the token list being scanned has been inserted as
  5719. the text expansion of a \.{\\count} or similar variable;
  5720. \hang|macro|, if a user-defined control sequence is being scanned;
  5721. \hang|output_text|, if an \.{\\output} routine is being scanned;
  5722. \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
  5723. \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
  5724. \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
  5725. \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
  5726. \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
  5727. \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
  5728. \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
  5729. \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
  5730. \hang|write_text|, if the text of a \.{\\write} is being scanned.
  5731. \yskip\noindent
  5732. The codes for |output_text|, |every_par_text|, etc., are equal to a constant
  5733. plus the corresponding codes for token list parameters |output_routine_loc|,
  5734. |every_par_loc|, etc.  The token list begins with a reference count if and
  5735. only if |token_type>=macro|.
  5736. @^reference counts@>
  5737. @d token_list=0 {|state| code when scanning a token list}
  5738. @d token_type==index {type of current token list}
  5739. @d param_start==limit {base of macro parameters in |param_stack|}
  5740. @d parameter=0 {|token_type| code for parameter}
  5741. @d u_template=1 {|token_type| code for \<u_j> template}
  5742. @d v_template=2 {|token_type| code for \<v_j> template}
  5743. @d backed_up=3 {|token_type| code for text to be reread}
  5744. @d inserted=4 {|token_type| code for inserted texts}
  5745. @d macro=5 {|token_type| code for defined control sequences}
  5746. @d output_text=6 {|token_type| code for output routines}
  5747. @d every_par_text=7 {|token_type| code for \.{\\everypar}}
  5748. @d every_math_text=8 {|token_type| code for \.{\\everymath}}
  5749. @d every_display_text=9 {|token_type| code for \.{\\everydisplay}}
  5750. @d every_hbox_text=10 {|token_type| code for \.{\\everyhbox}}
  5751. @d every_vbox_text=11 {|token_type| code for \.{\\everyvbox}}
  5752. @d every_job_text=12 {|token_type| code for \.{\\everyjob}}
  5753. @d every_cr_text=13 {|token_type| code for \.{\\everycr}}
  5754. @d mark_text=14 {|token_type| code for \.{\\topmark}, etc.}
  5755. @d write_text=15 {|token_type| code for \.{\\write}}
  5756. @ The |param_stack| is an auxiliary array used to hold pointers to the token
  5757. lists for parameters at the current level and subsidiary levels of input.
  5758. This stack is maintained with convention (2), and it grows at a different
  5759. rate from the others.
  5760. @<Glob...@>=
  5761. @!param_stack:array [0..param_size] of pointer;
  5762.   {token list pointers for parameters}
  5763. @!param_ptr:0..param_size; {first unused entry in |param_stack|}
  5764. @!max_param_stack:integer;
  5765.   {largest value of |param_ptr|, will be |<=param_size+9|}
  5766. @ The input routines must also interact with the processing of
  5767. \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
  5768. \.{\\cr} in certain places is supposed to trigger the beginning of special
  5769. \<v_j> template text in the scanner. This magic is accomplished by an
  5770. |align_state| variable that is increased by~1 when a `\.{\char'173}' is
  5771. scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
  5772. is nonzero during the \<u_j> template, after which it is set to zero; the
  5773. \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
  5774. |align_state=0|.
  5775. @<Glob...@>=
  5776. @!align_state:integer; {group level with respect to current alignment}
  5777. @ Thus, the ``current input state'' can be very complicated indeed; there
  5778. can be many levels and each level can arise in a variety of ways. The
  5779. |show_context| procedure, which is used by \TeX's error-reporting routine to
  5780. print out the current input state on all levels down to the most recent
  5781. line of characters from an input file, illustrates most of these conventions.
  5782. The global variable |base_ptr| contains the lowest level that was
  5783. displayed by this procedure.
  5784. @<Glob...@>=
  5785. @!base_ptr:0..stack_size; {shallowest level shown by |show_context|}
  5786. @ The status at each level is indicated by printing two lines, where the first
  5787. line indicates what was read so far and the second line shows what remains
  5788. to be read. The context is cropped, if necessary, so that the first line
  5789. contains at most |half_error_line| characters, and the second contains
  5790. at most |error_line|. Non-current input levels whose |token_type| is
  5791. `|backed_up|' are shown only if they have not been fully read.
  5792. @p procedure show_context; {prints where the scanner is}
  5793. label done;
  5794. var old_setting:0..max_selector; {saved |selector| setting}
  5795. @!nn:integer; {number of contexts shown so far, less one}
  5796. @!bottom_line:boolean; {have we reached the final context to be shown?}
  5797. @<Local variables for formatting calculations@>@/
  5798. begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
  5799.   {store current state}
  5800. nn:=-1; bottom_line:=false;
  5801. loop@+begin cur_input:=input_stack[base_ptr]; {enter into the context}
  5802.   if (state<>token_list) then
  5803.     if (name>17) or (base_ptr=0) then bottom_line:=true;
  5804.   if (base_ptr=input_ptr)or bottom_line or(nn<error_context_lines) then
  5805.     @<Display the current context@>
  5806.   else if nn=error_context_lines then
  5807.     begin print_nl("..."); incr(nn); {omitted if |error_context_lines<0|}
  5808.     end;
  5809.   if bottom_line then goto done;
  5810.   decr(base_ptr);
  5811.   end;
  5812. done: cur_input:=input_stack[input_ptr]; {restore original state}
  5813. @ @<Display the current context@>=
  5814. begin if (base_ptr=input_ptr) or (state<>token_list) or
  5815.    (token_type<>backed_up) or (loc<>null) then
  5816.     {we omit backed-up token lists that have already been read}
  5817.   begin tally:=0; {get ready to count characters}
  5818.   old_setting:=selector;
  5819.   if state<>token_list then
  5820.     begin @<Print location of current line@>;
  5821.     @<Pseudoprint the line@>;
  5822.     end
  5823.   else  begin @<Print type of token list@>;
  5824.     @<Pseudoprint the token list@>;
  5825.     end;
  5826.   selector:=old_setting; {stop pseudoprinting}
  5827.   @<Print two lines using the tricky pseudoprinted information@>;
  5828.   incr(nn);
  5829.   end;
  5830. @ This routine should be changed, if necessary, to give the best possible
  5831. indication of where the current line resides in the input file.
  5832. For example, on some systems it is best to print both a page and line number.
  5833. @^system dependencies@>
  5834. @<Print location of current line@>=
  5835. if name<=17 then
  5836.   if terminal_input then
  5837.     if base_ptr=0 then print_nl("<*>") else print_nl("<insert> ")
  5838.   else  begin print_nl("<read ");
  5839.     if name=17 then print_char("*")@+else print_int(name-1);
  5840. @.*\relax@>
  5841.     print_char(">");
  5842.     end
  5843. else  begin print_nl("l."); print_int(line);
  5844.   end;
  5845. print_char(" ")
  5846. @ @<Print type of token list@>=
  5847. case token_type of
  5848. parameter: print_nl("<argument> ");
  5849. u_template,v_template: print_nl("<template> ");
  5850. backed_up: if loc=null then print_nl("<recently read> ")
  5851.   else print_nl("<to be read again> ");
  5852. inserted: print_nl("<inserted text> ");
  5853. macro: begin print_ln; print_cs(name);
  5854.   end;
  5855. output_text: print_nl("<output> ");
  5856. every_par_text: print_nl("<everypar> ");
  5857. every_math_text: print_nl("<everymath> ");
  5858. every_display_text: print_nl("<everydisplay> ");
  5859. every_hbox_text: print_nl("<everyhbox> ");
  5860. every_vbox_text: print_nl("<everyvbox> ");
  5861. every_job_text: print_nl("<everyjob> ");
  5862. every_cr_text: print_nl("<everycr> ");
  5863. mark_text: print_nl("<mark> ");
  5864. write_text: print_nl("<write> ");
  5865. othercases print_nl("?") {this should never happen}
  5866. endcases
  5867. @ Here it is necessary to explain a little trick. We don't want to store a long
  5868. string that corresponds to a token list, because that string might take up
  5869. lots of memory; and we are printing during a time when an error message is
  5870. being given, so we dare not do anything that might overflow one of \TeX's
  5871. tables. So `pseudoprinting' is the answer: We enter a mode of printing
  5872. that stores characters into a buffer of length |error_line|, where character
  5873. $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
  5874. |k<trick_count|, otherwise character |k| is dropped. Initially we set
  5875. |tally:=0| and |trick_count:=1000000|; then when we reach the
  5876. point where transition from line 1 to line 2 should occur, we
  5877. set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
  5878. tally+1+error_line-half_error_line)|. At the end of the
  5879. pseudoprinting, the values of |first_count|, |tally|, and
  5880. |trick_count| give us all the information we need to print the two lines,
  5881. and all of the necessary text is in |trick_buf|.
  5882. Namely, let |l| be the length of the descriptive information that appears
  5883. on the first line. The length of the context information gathered for that
  5884. line is |k=first_count|, and the length of the context information
  5885. gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
  5886. where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
  5887. descriptive information on line~1, and set |n:=l+k|; here |n| is the
  5888. length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
  5889. and print `\.{...}' followed by
  5890. $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
  5891. where subscripts of |trick_buf| are circular modulo |error_line|. The
  5892. second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
  5893. unless |n+m>error_line|; in the latter case, further cropping is done.
  5894. This is easier to program than to explain.
  5895. @<Local variables for formatting...@>=
  5896. @!i:0..buf_size; {index into |buffer|}
  5897. @!j:0..buf_size; {end of current line in |buffer|}
  5898. @!l:0..half_error_line; {length of descriptive information on line 1}
  5899. @!m:integer; {context information gathered for line 2}
  5900. @!n:0..error_line; {length of line 1}
  5901. @!p: integer; {starting or ending place in |trick_buf|}
  5902. @!q: integer; {temporary index}
  5903. @ The following code sets up the print routines so that they will gather
  5904. the desired information.
  5905. @d begin_pseudoprint==
  5906.   begin l:=tally; tally:=0; selector:=pseudo;
  5907.   trick_count:=1000000;
  5908.   end
  5909. @d set_trick_count==
  5910.   begin first_count:=tally;
  5911.   trick_count:=tally+1+error_line-half_error_line;
  5912.   if trick_count<error_line then trick_count:=error_line;
  5913.   end
  5914. @ And the following code uses the information after it has been gathered.
  5915. @<Print two lines using the tricky pseudoprinted information@>=
  5916. if trick_count=1000000 then set_trick_count;
  5917.   {|set_trick_count| must be performed}
  5918. if tally<trick_count then m:=tally-first_count
  5919. else m:=trick_count-first_count; {context on line 2}
  5920. if l+first_count<=half_error_line then
  5921.   begin p:=0; n:=l+first_count;
  5922.   end
  5923. else  begin print("..."); p:=l+first_count-half_error_line+3;
  5924.   n:=half_error_line;
  5925.   end;
  5926. for q:=p to first_count-1 do print_char(trick_buf[q mod error_line]);
  5927. print_ln;
  5928. for q:=1 to n do print_char(" "); {print |n| spaces to begin line~2}
  5929. if m+n<=error_line then p:=first_count+m else p:=first_count+(error_line-n-3);
  5930. for q:=first_count to p-1 do print_char(trick_buf[q mod error_line]);
  5931. if m+n>error_line then print("...")
  5932. @ But the trick is distracting us from our current goal, which is to
  5933. understand the input state. So let's concentrate on the data structures that
  5934. are being pseudoprinted as we finish up the |show_context| procedure.
  5935. @<Pseudoprint the line@>=
  5936. begin_pseudoprint;
  5937. if buffer[limit]=end_line_char then j:=limit
  5938. else j:=limit+1; {determine the effective end of the line}
  5939. if j>0 then for i:=start to j-1 do
  5940.   begin if i=loc then set_trick_count;
  5941.   print(buffer[i]);
  5942.   end
  5943. @ @<Pseudoprint the token list@>=
  5944. begin_pseudoprint;
  5945. if token_type<macro then show_token_list(start,loc,100000)
  5946. else show_token_list(link(start),loc,100000) {avoid reference count}
  5947. @ Here is the missing piece of |show_token_list| that is activated when the
  5948. token beginning line~2 is about to be shown:
  5949. @<Do magic computation@>=set_trick_count
  5950. @* \[23] Maintaining the input stacks.
  5951. The following subroutines change the input status in commonly needed ways.
  5952. First comes |push_input|, which stores the current state and creates a
  5953. new level (having, initially, the same properties as the old).
  5954. @d push_input==@t@> {enter a new input level, save the old}
  5955.   begin if input_ptr>max_in_stack then
  5956.     begin max_in_stack:=input_ptr;
  5957.     if input_ptr=stack_size then overflow("input stack size",stack_size);
  5958. @:TeX capacity exceeded input stack size}{\quad input stack size@>
  5959.     end;
  5960.   input_stack[input_ptr]:=cur_input; {stack the record}
  5961.   incr(input_ptr);
  5962.   end
  5963. @ And of course what goes up must come down.
  5964. @d pop_input==@t@> {leave an input level, re-enter the old}
  5965.   begin decr(input_ptr); cur_input:=input_stack[input_ptr];
  5966.   end
  5967. @ Here is a procedure that starts a new level of token-list input, given
  5968. a token list |p| and its type |t|. If |t=macro|, the calling routine should
  5969. set |name| and |loc|.
  5970. @d back_list(#)==begin_token_list(#,backed_up) {backs up a simple token list}
  5971. @d ins_list(#)==begin_token_list(#,inserted) {inserts a simple token list}
  5972. @p procedure begin_token_list(@!p:pointer;@!t:quarterword);
  5973. begin push_input; state:=token_list; start:=p; token_type:=t;
  5974. if t>=macro then {the token list starts with a reference count}
  5975.   begin add_token_ref(p);
  5976.   if t=macro then param_start:=param_ptr
  5977.   else  begin loc:=link(p);
  5978.     if tracing_macros>1 then
  5979.       begin begin_diagnostic; print_nl("");
  5980.       case t of
  5981.       mark_text:print_esc("mark");
  5982.       write_text:print_esc("write");
  5983.       othercases print_cmd_chr(assign_toks,t-output_text+output_routine_loc)
  5984.       endcases;@/
  5985.       print("->"); token_show(p); end_diagnostic(false);
  5986.       end;
  5987.     end;
  5988.   end
  5989. else loc:=p;
  5990. @ When a token list has been fully scanned, the following computations
  5991. should be done as we leave that level of input. The |token_type| tends
  5992. to be equal to either |backed_up| or |inserted| about 2/3 of the time.
  5993. @^inner loop@>
  5994. @p procedure end_token_list; {leave a token-list input level}
  5995. begin if token_type>=backed_up then {token list to be deleted}
  5996.   begin if token_type<=inserted then flush_list(start)
  5997.   else  begin delete_token_ref(start); {update reference count}
  5998.     if token_type=macro then {parameters must be flushed}
  5999.       while param_ptr>param_start do
  6000.         begin decr(param_ptr);
  6001.         flush_list(param_stack[param_ptr]);
  6002.         end;
  6003.     end;
  6004.   end
  6005. else if token_type=u_template then
  6006.   if align_state>500000 then align_state:=0
  6007.   else fatal_error("(interwoven alignment preambles are not allowed)");
  6008. @.interwoven alignment preambles...@>
  6009. pop_input;
  6010. check_interrupt;
  6011. @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
  6012. seen. The |back_input| procedure takes care of this by putting the token
  6013. just scanned back into the input stream, ready to be read again. This
  6014. procedure can be used only if |cur_tok| represents the token to be
  6015. replaced. Some applications of \TeX\ use this procedure a lot,
  6016. so it has been slightly optimized for speed.
  6017. @^inner loop@>
  6018. @p procedure back_input; {undoes one token of input}
  6019. var p:pointer; {a token list of length one}
  6020. begin while (state=token_list)and(loc=null) do
  6021.   end_token_list; {conserve stack space}
  6022. p:=get_avail; info(p):=cur_tok;
  6023. if cur_tok<right_brace_limit then
  6024.   if cur_tok<left_brace_limit then decr(align_state)
  6025.   else incr(align_state);
  6026. push_input; state:=token_list; start:=p; token_type:=backed_up;
  6027. loc:=p; {that was |back_list(p)|, without procedure overhead}
  6028. @ @<Insert token |p| into \TeX's input@>=
  6029. begin t:=cur_tok; cur_tok:=p; back_input; cur_tok:=t;
  6030. @ The |back_error| routine is used when we want to replace an offending token
  6031. just before issuing an error message. This routine, like |back_input|,
  6032. requires that |cur_tok| has been set. We disable interrupts during the
  6033. call of |back_input| so that the help message won't be lost.
  6034. @p procedure back_error; {back up one token and call |error|}
  6035. begin OK_to_interrupt:=false; back_input; OK_to_interrupt:=true; error;
  6036. procedure ins_error; {back up one inserted token and call |error|}
  6037. begin OK_to_interrupt:=false; back_input; token_type:=inserted;
  6038. OK_to_interrupt:=true; error;
  6039. @ The |begin_file_reading| procedure starts a new level of input for lines
  6040. of characters to be read from a file, or as an insertion from the
  6041. terminal. It does not take care of opening the file, nor does it set |loc|
  6042. or |limit| or |line|.
  6043. @^system dependencies@>
  6044. @p procedure begin_file_reading;
  6045. begin if in_open=max_in_open then overflow("text input levels",max_in_open);
  6046. @:TeX capacity exceeded text input levels}{\quad text input levels@>
  6047. if first=buf_size then overflow("buffer size",buf_size);
  6048. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  6049. incr(in_open); push_input; index:=in_open;
  6050. line_stack[index]:=line; start:=first; state:=mid_line;
  6051. name:=0; {|terminal_input| is now |true|}
  6052. @ Conversely, the variables must be downdated when such a level of input
  6053. is finished:
  6054. @p procedure end_file_reading;
  6055. begin first:=start; line:=line_stack[index];
  6056. if name>17 then a_close(cur_file); {forget it}
  6057. pop_input; decr(in_open);
  6058. @ In order to keep the stack from overflowing during a long sequence of
  6059. inserted `\.{\\show}' commands, the following routine removes completed
  6060. error-inserted lines from memory.
  6061. @p procedure clear_for_error_prompt;
  6062. begin while (state<>token_list)and terminal_input and@|
  6063.   (input_ptr>0)and(loc>limit) do end_file_reading;
  6064. print_ln; clear_terminal;
  6065. @ To get \TeX's whole input mechanism going, we perform the following
  6066. actions.
  6067. @<Initialize the input routines@>=
  6068. begin input_ptr:=0; max_in_stack:=0;
  6069. in_open:=0; open_parens:=0; max_buf_stack:=0;
  6070. param_ptr:=0; max_param_stack:=0;
  6071. first:=buf_size; repeat buffer[first]:=0; decr(first); until first=0;
  6072. scanner_status:=normal; warning_index:=null; first:=1;
  6073. state:=new_line; start:=1; index:=0; line:=0; name:=0;
  6074. force_eof:=false;
  6075. align_state:=1000000;@/
  6076. if not init_terminal then goto final_end;
  6077. limit:=last; first:=last+1; {|init_terminal| has set |loc| and |last|}
  6078. @* \[24] Getting the next token.
  6079. The heart of \TeX's input mechanism is the |get_next| procedure, which
  6080. we shall develop in the next few sections of the program. Perhaps we
  6081. shouldn't actually call it the ``heart,'' however, because it really acts
  6082. as \TeX's eyes and mouth, reading the source files and gobbling them up.
  6083. And it also helps \TeX\ to regurgitate stored token lists that are to be
  6084. processed again.
  6085. @^eyes and mouth@>
  6086. The main duty of |get_next| is to input one token and to set |cur_cmd|
  6087. and |cur_chr| to that token's command code and modifier. Furthermore, if
  6088. the input token is a control sequence, the |eqtb| location of that control
  6089. sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
  6090. Underlying this simple description is a certain amount of complexity
  6091. because of all the cases that need to be handled.
  6092. However, the inner loop of |get_next| is reasonably short and fast.
  6093. When |get_next| is asked to get the next token of a \.{\\read} line,
  6094. it sets |cur_cmd=cur_chr=cur_cs=0| in the case that no more tokens
  6095. appear on that line. (There might not be any tokens at all, if the
  6096. |end_line_char| has |ignore| as its catcode.)
  6097. @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
  6098. is needed because a blank line of input is supposed to be exactly equivalent
  6099. to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
  6100. when detecting a blank line.
  6101. @<Glob...@>=
  6102. @!par_loc:pointer; {location of `\.{\\par}' in |eqtb|}
  6103. @!par_token:halfword; {token representing `\.{\\par}'}
  6104. @ @<Put each...@>=
  6105. primitive("par",par_end,256); {cf. |scan_file_name|}
  6106. @!@:par_}{\.{\\par} primitive@>
  6107. par_loc:=cur_val; par_token:=cs_token_flag+par_loc;
  6108. @ @<Cases of |print_cmd_chr|...@>=
  6109. par_end:print_esc("par");
  6110. @ Before getting into |get_next|, let's consider the subroutine that
  6111. is called when an `\.{\\outer}' control sequence has been scanned or
  6112. when the end of a file has been reached. These two cases are distinguished
  6113. by |cur_cs|, which is zero at the end of a file.
  6114. @p procedure check_outer_validity;
  6115. var p:pointer; {points to inserted token list}
  6116. @!q:pointer; {auxiliary pointer}
  6117. begin if scanner_status<>normal then
  6118.   begin deletions_allowed:=false;
  6119.   @<Back up an outer control sequence so that it can be reread@>;
  6120.   if scanner_status>skipping then
  6121.     @<Tell the user what has run away and try to recover@>
  6122.   else  begin print_err("Incomplete "); print_cmd_chr(if_test,cur_if);
  6123. @.Incomplete \\if...@>
  6124.     print("; all text was ignored after line "); print_int(skip_line);
  6125.     help3("A forbidden control sequence occurred in skipped text.")@/
  6126.     ("This kind of error happens when you say `\if...' and forget")@/
  6127.     ("the matching `\fi'. I've inserted a `\fi'; this might work.");
  6128.     if cur_cs<>0 then cur_cs:=0
  6129.     else help_line[2]:=@|
  6130.       "The file ended while I was skipping conditional text.";
  6131.     cur_tok:=cs_token_flag+frozen_fi; ins_error;
  6132.     end;
  6133.   deletions_allowed:=true;
  6134.   end;
  6135. @ An outer control sequence that occurs in a \.{\\read} will not be reread,
  6136. since the error recovery for \.{\\read} is not very powerful.
  6137. @<Back up an outer control sequence so that it can be reread@>=
  6138. if cur_cs<>0 then
  6139.   begin if (state=token_list)or(name<1)or(name>17) then
  6140.     begin p:=get_avail; info(p):=cs_token_flag+cur_cs;
  6141.     back_list(p); {prepare to read the control sequence again}
  6142.     end;
  6143.   cur_cmd:=spacer; cur_chr:=" "; {replace it by a space}
  6144.   end
  6145. @ @<Tell the user what has run away...@>=
  6146. begin runaway; {print a definition, argument, or preamble}
  6147. if cur_cs=0 then print_err("File ended")
  6148. @.File ended while scanning...@>
  6149. else  begin cur_cs:=0; print_err("Forbidden control sequence found");
  6150. @.Forbidden control sequence...@>
  6151.   end;
  6152. print(" while scanning ");
  6153. @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
  6154.   and insert tokens that should lead to recovery@>;
  6155. print(" of "); sprint_cs(warning_index);
  6156. help4("I suspect you have forgotten a `}', causing me")@/
  6157. ("to read past where you wanted me to stop.")@/
  6158. ("I'll try to recover; but if the error is serious,")@/
  6159. ("you'd better type `E' or `X' now and fix your file.");@/
  6160. error;
  6161. @ The recovery procedure can't be fully understood without knowing more
  6162. about the \TeX\ routines that should be aborted, but we can sketch the
  6163. ideas here:  For a runaway definition we will insert a right brace; for a
  6164. runaway preamble, we will insert a special \.{\\cr} token and a right
  6165. brace; and for a runaway argument, we will set |long_state| to
  6166. |outer_call| and insert \.{\\par}.
  6167. @<Print either `\.{definition}' or ...@>=
  6168. p:=get_avail;
  6169. case scanner_status of
  6170. defining:begin print("definition"); info(p):=right_brace_token+"}";
  6171.   end;
  6172. matching:begin print("use"); info(p):=par_token; long_state:=outer_call;
  6173.   end;
  6174. aligning:begin print("preamble"); info(p):=right_brace_token+"}"; q:=p;
  6175.   p:=get_avail; link(p):=q; info(p):=cs_token_flag+frozen_cr;
  6176.   align_state:=-1000000;
  6177.   end;
  6178. absorbing:begin print("text"); info(p):=right_brace_token+"}";
  6179.   end;
  6180. end; {there are no other cases}
  6181. ins_list(p)
  6182. @ We need to mention a procedure here that may be called by |get_next|.
  6183. @p procedure@?firm_up_the_line; forward;
  6184. @ Now we're ready to take the plunge into |get_next| itself. Parts of
  6185. this routine are executed more often than any other instructions of \TeX.
  6186. @^mastication@>@^inner loop@>
  6187. @d switch=25 {a label in |get_next|}
  6188. @d start_cs=26 {another}
  6189. @p procedure get_next; {sets |cur_cmd|, |cur_chr|, |cur_cs| to next token}
  6190. label restart, {go here to get the next input token}
  6191.   switch, {go here to eat the next character from a file}
  6192.   reswitch, {go here to digest it again}
  6193.   start_cs, {go here to start looking for a control sequence}
  6194.   found, {go here when a control sequence has been found}
  6195.   exit; {go here when the next input token has been got}
  6196. var k:0..buf_size; {an index into |buffer|}
  6197. @!t:halfword; {a token}
  6198. @!cat:0..15; {|cat_code(cur_chr)|, usually}
  6199. @!c,@!cc:ASCII_code; {constituents of a possible expanded code}
  6200. @!d:2..3; {number of excess characters in an expanded code}
  6201. begin restart: cur_cs:=0;
  6202. if state<>token_list then
  6203. @<Input from external file, |goto restart| if no input found@>
  6204. else @<Input from token list, |goto restart| if end of list or
  6205.   if a parameter needs to be expanded@>;
  6206. @<If an alignment entry has just ended, take appropriate action@>;
  6207. exit:end;
  6208. @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
  6209. current level of braces is the same as the level that was present at the
  6210. beginning of that alignment entry; i.e., provided that |align_state| has
  6211. returned to the value it had after the \<u_j> template for that entry.
  6212. @^inner loop@>
  6213. @<If an alignment entry has just ended, take appropriate action@>=
  6214. if cur_cmd<=car_ret then if cur_cmd>=tab_mark then if align_state=0 then
  6215.   @<Insert the \(v)\<v_j> template and |goto restart|@>
  6216. @ @<Input from external file, |goto restart| if no input found@>=
  6217. @^inner loop@>
  6218. begin switch: if loc<=limit then {current line not yet finished}
  6219.   begin cur_chr:=buffer[loc]; incr(loc);
  6220.   reswitch: cur_cmd:=cat_code(cur_chr);
  6221.   @<Change state if necessary, and |goto switch| if the
  6222.     current character should be ignored,
  6223.     or |goto reswitch| if the current character
  6224.     changes to another@>;
  6225.   end
  6226. else  begin state:=new_line;@/
  6227.   @<Move to next line of file,
  6228.     or |goto restart| if there is no next line,
  6229.     or |return| if a \.{\\read} line has finished@>;
  6230.   check_interrupt;
  6231.   goto switch;
  6232.   end;
  6233. @ The following 48-way switch accomplishes the scanning quickly, assuming
  6234. that a decent \PASCAL\ compiler has translated the code. Note that the numeric
  6235. values for |mid_line|, |skip_blanks|, and |new_line| are spaced
  6236. apart from each other by |max_char_code+1|, so we can add a character's
  6237. command code to the state to get a single number that characterizes both.
  6238. @d any_state_plus(#) == mid_line+#,skip_blanks+#,new_line+#
  6239. @<Change state if necessary...@>=
  6240. case state+cur_cmd of
  6241. @<Cases where character is ignored@>: goto switch;
  6242. any_state_plus(escape): @<Scan a control sequence
  6243.   and set |state:=skip_blanks| or |mid_line|@>;
  6244. any_state_plus(active_char): @<Process an active-character control sequence
  6245.   and set |state:=mid_line|@>;
  6246. any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
  6247.   like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|,
  6248.   otherwise set |state:=mid_line|@>;
  6249. any_state_plus(invalid_char): @<Decry the invalid character and
  6250.   |goto restart|@>;
  6251. @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
  6252. othercases do_nothing
  6253. endcases
  6254. @ @<Cases where character is ignored@>=
  6255. any_state_plus(ignore),skip_blanks+spacer,new_line+spacer
  6256. @ We go to |restart| instead of to |switch|, because |state| might equal
  6257. |token_list| after the error has been dealt with
  6258. (cf.\ |clear_for_error_prompt|).
  6259. @<Decry the invalid...@>=
  6260. begin print_err("Text line contains an invalid character");
  6261. @.Text line contains...@>
  6262. help2("A funny symbol that I can't read has just been input.")@/
  6263. ("Continue, and I'll forget that it ever happened.");@/
  6264. deletions_allowed:=false; error; deletions_allowed:=true;
  6265. goto restart;
  6266. @ @d add_delims_to(#)==#+math_shift,#+tab_mark,#+mac_param,
  6267.   #+sub_mark,#+letter,#+other_char
  6268. @<Handle situations involving spaces, braces, changes of state@>=
  6269. mid_line+spacer:@<Enter |skip_blanks| state, emit a space@>;
  6270. mid_line+car_ret:@<Finish line, emit a space@>;
  6271. skip_blanks+car_ret,any_state_plus(comment):
  6272.   @<Finish line, |goto switch|@>;
  6273. new_line+car_ret:@<Finish line, emit a \.{\\par}@>;
  6274. mid_line+left_brace: incr(align_state);
  6275. skip_blanks+left_brace,new_line+left_brace: begin
  6276.   state:=mid_line; incr(align_state);
  6277.   end;
  6278. mid_line+right_brace: decr(align_state);
  6279. skip_blanks+right_brace,new_line+right_brace: begin
  6280.   state:=mid_line; decr(align_state);
  6281.   end;
  6282. add_delims_to(skip_blanks),add_delims_to(new_line): state:=mid_line;
  6283. @ When a character of type |spacer| gets through, its character code is
  6284. changed to $\.{"\ "}=@'40$. This means that the ASCII codes for tab and space,
  6285. and for the space inserted at the end of a line, will
  6286. be treated alike when macro parameters are being matched. We do this
  6287. since such characters are indistinguishable on most computer terminal displays.
  6288. @<Finish line, emit a space@>=
  6289. begin loc:=limit+1; cur_cmd:=spacer; cur_chr:=" ";
  6290. @ The following code is performed only when |cur_cmd=spacer|.
  6291. @<Enter |skip_blanks| state, emit a space@>=
  6292. begin state:=skip_blanks; cur_chr:=" ";
  6293. @ @<Finish line, |goto switch|@>=
  6294. begin loc:=limit+1; goto switch;
  6295. @ @<Finish line, emit a \.{\\par}@>=
  6296. begin loc:=limit+1; cur_cs:=par_loc; cur_cmd:=eq_type(cur_cs);
  6297. cur_chr:=equiv(cur_cs);
  6298. if cur_cmd>=outer_call then check_outer_validity;
  6299. @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
  6300. @d is_hex(#)==(((#>="0")and(#<="9"))or((#>="a")and(#<="f")))
  6301. @d hex_to_cur_chr==
  6302.   if c<="9" then cur_chr:=c-"0" @+else cur_chr:=c-"a"+10;
  6303.   if cc<="9" then cur_chr:=16*cur_chr+cc-"0"
  6304.   else cur_chr:=16*cur_chr+cc-"a"+10
  6305. @<If this |sup_mark| starts an expanded character...@>=
  6306. begin if cur_chr=buffer[loc] then if loc<limit then
  6307.   begin c:=buffer[loc+1]; @+if c<@'200 then {yes we have an expanded char}
  6308.     begin loc:=loc+2; 
  6309.     if is_hex(c) then if loc<=limit then
  6310.       begin cc:=buffer[loc]; @+if is_hex(cc) then
  6311.         begin incr(loc); hex_to_cur_chr; goto reswitch;
  6312.         end;
  6313.       end;
  6314.     if c<@'100 then cur_chr:=c+@'100 @+else cur_chr:=c-@'100;
  6315.     goto reswitch;
  6316.     end;
  6317.   end;
  6318. state:=mid_line;
  6319. @ @<Process an active-character...@>=
  6320. begin cur_cs:=cur_chr+active_base;
  6321. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs); state:=mid_line;
  6322. if cur_cmd>=outer_call then check_outer_validity;
  6323. @ Control sequence names are scanned only when they appear in some line of
  6324. a file; once they have been scanned the first time, their |eqtb| location
  6325. serves as a unique identification, so \TeX\ doesn't need to refer to the
  6326. original name any more except when it prints the equivalent in symbolic form.
  6327. The program that scans a control sequence has been written carefully
  6328. in order to avoid the blowups that might otherwise occur if a malicious
  6329. user tried something like `\.{\\catcode\'15=0}'. The algorithm might
  6330. look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
  6331. If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
  6332. appear in or just following
  6333. a control sequence name, they are converted to single characters in the
  6334. buffer and the process is repeated, slowly but surely.
  6335. @<Scan a control...@>=
  6336. begin if loc>limit then cur_cs:=null_cs {|state| is irrelevant in this case}
  6337. else  begin start_cs: k:=loc; cur_chr:=buffer[k]; cat:=cat_code(cur_chr);
  6338.   incr(k);
  6339.   if cat=letter then state:=skip_blanks
  6340.   else if cat=spacer then state:=skip_blanks
  6341.   else state:=mid_line;
  6342.   if (cat=letter)and(k<=limit) then
  6343.     @<Scan ahead in the buffer until finding a nonletter;
  6344.     if an expanded code is encountered, reduce it
  6345.     and |goto start_cs|; otherwise if a multiletter control
  6346.     sequence is found, adjust |cur_cs| and |loc|, and
  6347.     |goto found|@>
  6348.   else @<If an expanded code is present, reduce it and |goto start_cs|@>;
  6349.   cur_cs:=single_base+buffer[loc]; incr(loc);
  6350.   end;
  6351. found: cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6352. if cur_cmd>=outer_call then check_outer_validity;
  6353. @ Whenever we reach the following piece of code, we will have
  6354. |cur_chr=buffer[k-1]| and |k<=limit+1| and |cat=cat_code(cur_chr)|. If an
  6355. expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)..(k+1)]|
  6356. or |buffer[(k-1)..(k+2)]|, we
  6357. will store the corresponding code in |buffer[k-1]| and shift the rest of
  6358. the buffer left two or three places.
  6359. @<If an expanded...@>=
  6360. begin if buffer[k]=cur_chr then @+if cat=sup_mark then @+if k<limit then
  6361.   begin c:=buffer[k+1]; @+if c<@'200 then {yes, one is indeed present}
  6362.     begin d:=2;
  6363.     if is_hex(c) then @+if k+2<=limit then
  6364.       begin cc:=buffer[k+2]; @+if is_hex(cc) then incr(d);
  6365.       end;
  6366.     if d>2 then
  6367.       begin hex_to_cur_chr; buffer[k-1]:=cur_chr;
  6368.       end
  6369.     else if c<@'100 then buffer[k-1]:=c+@'100
  6370.     else buffer[k-1]:=c-@'100;
  6371.     limit:=limit-d; first:=first-d;
  6372.     while k<=limit do
  6373.       begin buffer[k]:=buffer[k+d]; incr(k);
  6374.       end;
  6375.     goto start_cs;
  6376.     end;
  6377.   end;
  6378. @ @<Scan ahead in the buffer...@>=
  6379. begin repeat cur_chr:=buffer[k]; cat:=cat_code(cur_chr); incr(k);
  6380. until (cat<>letter)or(k>limit);
  6381. @<If an expanded...@>;
  6382. if cat<>letter then decr(k);
  6383.   {now |k| points to first nonletter}
  6384. if k>loc+1 then {multiletter control sequence has been scanned}
  6385.   begin cur_cs:=id_lookup(loc,k-loc); loc:=k; goto found;
  6386.   end;
  6387. @ Let's consider now what happens when |get_next| is looking at a token list.
  6388. @<Input from token list, |goto restart| if end of list or
  6389.   if a parameter needs to be expanded@>=
  6390. if loc<>null then {list not exhausted}
  6391. @^inner loop@>
  6392.   begin t:=info(loc); loc:=link(loc); {move to next}
  6393.   if t>=cs_token_flag then {a control sequence token}
  6394.     begin cur_cs:=t-cs_token_flag;
  6395.     cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6396.     if cur_cmd>=outer_call then
  6397.       if cur_cmd=dont_expand then
  6398.         @<Get the next token, suppressing expansion@>
  6399.       else check_outer_validity;
  6400.     end
  6401.   else  begin cur_cmd:=t div @'400; cur_chr:=t mod @'400;
  6402.     case cur_cmd of
  6403.     left_brace: incr(align_state);
  6404.     right_brace: decr(align_state);
  6405.     out_param: @<Insert macro parameter and |goto restart|@>;
  6406.     othercases do_nothing
  6407.     endcases;
  6408.     end;
  6409.   end
  6410. else  begin {we are done with this token list}
  6411.   end_token_list; goto restart; {resume previous level}
  6412.   end
  6413. @ The present point in the program is reached only when the |expand|
  6414. routine has inserted a special marker into the input. In this special
  6415. case, |info(loc)| is known to be a control sequence token, and |link(loc)=null|.
  6416. @d no_expand_flag=257 {this characterizes a special variant of |relax|}
  6417. @<Get the next token, suppressing expansion@>=
  6418. begin cur_cs:=info(loc)-cs_token_flag; loc:=null;@/
  6419. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6420. if cur_cmd>max_command then
  6421.   begin cur_cmd:=relax; cur_chr:=no_expand_flag;
  6422.   end;
  6423. @ @<Insert macro parameter...@>=
  6424. begin begin_token_list(param_stack[param_start+cur_chr-1],parameter);
  6425. goto restart;
  6426. @ All of the easy branches of |get_next| have now been taken care of.
  6427. There is one more branch.
  6428. @d end_line_char_inactive == (end_line_char<0)or(end_line_char>255)
  6429. @<Move to next line of file, or |goto restart|...@>=
  6430. if name>17 then @<Read next line of file into |buffer|, or
  6431.   |goto restart| if the file has ended@>
  6432. else  begin if not terminal_input then {\.{\\read} line has ended}
  6433.     begin cur_cmd:=0; cur_chr:=0; return;
  6434.     end;
  6435.   if input_ptr>0 then {text was inserted during error recovery}
  6436.     begin end_file_reading; goto restart; {resume previous level}
  6437.     end;
  6438.   if selector<log_only then open_log_file;
  6439.   if interaction>nonstop_mode then
  6440.     begin if end_line_char_inactive then incr(limit);
  6441.     if limit=start then {previous line was empty}
  6442.       print_nl("(Please type a command or say `\end')");
  6443. @.Please type...@>
  6444.     print_ln; first:=start;
  6445.     prompt_input("*"); {input on-line into |buffer|}
  6446. @.*\relax@>
  6447.     limit:=last;
  6448.     if end_line_char_inactive then decr(limit)
  6449.     else  buffer[limit]:=end_line_char;
  6450.     first:=limit+1;
  6451.     loc:=start;
  6452.     end
  6453.   else fatal_error("*** (job aborted, no legal \end found)");
  6454. @.job aborted@>
  6455.     {nonstop mode, which is intended for overnight batch processing,
  6456.     never waits for on-line input}
  6457.   end
  6458. @ The global variable |force_eof| is normally |false|; it is set |true|
  6459. by an \.{\\endinput} command.
  6460. @<Glob...@>=
  6461. @!force_eof:boolean; {should the next \.{\\input} be aborted early?}
  6462. @ @<Read next line of file into |buffer|, or
  6463.   |goto restart| if the file has ended@>=
  6464. begin incr(line); first:=start;
  6465. if not force_eof then
  6466.   begin if input_ln(cur_file,true) then {not end of file}
  6467.     firm_up_the_line {this sets |limit|}
  6468.   else force_eof:=true;
  6469.   end;
  6470. if force_eof then
  6471.   begin print_char(")"); decr(open_parens);
  6472.   update_terminal; {show user that file has been read}
  6473.   force_eof:=false;
  6474.   end_file_reading; {resume previous level}
  6475.   check_outer_validity; goto restart;
  6476.   end;
  6477. if end_line_char_inactive then decr(limit)
  6478. else  buffer[limit]:=end_line_char;
  6479. first:=limit+1; loc:=start; {ready to read}
  6480. @ If the user has set the |pausing| parameter to some positive value,
  6481. and if nonstop mode has not been selected, each line of input is displayed
  6482. on the terminal and the transcript file, followed by `\.{=>}'.
  6483. \TeX\ waits for a response. If the response is simply |carriage_return|, the
  6484. line is accepted as it stands, otherwise the line typed is
  6485. used instead of the line in the file.
  6486. @p procedure firm_up_the_line;
  6487. var k:0..buf_size; {an index into |buffer|}
  6488. begin limit:=last;
  6489. if pausing>0 then if interaction>nonstop_mode then
  6490.   begin wake_up_terminal; print_ln;
  6491.   if start<limit then for k:=start to limit-1 do print(buffer[k]);
  6492.   first:=limit; prompt_input("=>"); {wait for user response}
  6493. @.=>@>
  6494.   if last>first then
  6495.     begin for k:=first to last-1 do {move line down in buffer}
  6496.       buffer[k+start-first]:=buffer[k];
  6497.     limit:=start+last-first;
  6498.     end;
  6499.   end;
  6500. @ Since |get_next| is used so frequently in \TeX, it is convenient
  6501. to define three related procedures that do a little more:
  6502. \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
  6503. also sets |cur_tok|, a packed halfword version of the current token.
  6504. \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
  6505. |get_token|, but if the current token turns out to be a user-defined
  6506. control sequence (i.e., a macro call), or a conditional,
  6507. or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
  6508. it is eliminated from the input by beginning the expansion of the macro
  6509. or the evaluation of the conditional.
  6510. \yskip\hang|x_token| is like |get_x_token| except that it assumes that
  6511. |get_next| has already been called.
  6512. \yskip\noindent
  6513. In fact, these three procedures account for {\sl all\/} uses of |get_next|,
  6514. except for two places in the ``inner loop'' when |cur_tok| need not be set,
  6515. and except when the arguments to \.{\\ifx} are being scanned.
  6516. @ No new control sequences will be defined except during a call of
  6517. |get_token|, or when \.{\\csname} compresses a token list, because
  6518. |no_new_control_sequence| is always |true| at other times.
  6519. @p procedure get_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|}
  6520. begin no_new_control_sequence:=false; get_next; no_new_control_sequence:=true;
  6521. @^inner loop@>
  6522. if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6523. else cur_tok:=cs_token_flag+cur_cs;
  6524. @* \[25] Expanding the next token.
  6525. Only a dozen or so command codes |>max_command| can possibly be returned by
  6526. |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
  6527. |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
  6528. |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
  6529. |end_template|.{\emergencystretch=40pt\par}
  6530. The |expand| subroutine is used when |cur_cmd>max_command|. It removes a
  6531. ``call'' or a conditional or one of the other special operations just
  6532. listed.  It follows that |expand| might invoke itself recursively. In all
  6533. cases, |expand| destroys the current token, but it sets things up so that
  6534. the next |get_next| will deliver the appropriate next token. The value of
  6535. |cur_tok| need not be known when |expand| is called.
  6536. Since several of the basic scanning routines communicate via global variables,
  6537. their values are saved as local variables of |expand| so that
  6538. recursive calls don't invalidate them.
  6539. @^recursion@>
  6540. @p@t\4@>@<Declare the procedure called |macro_call|@>@;@/
  6541. @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
  6542. procedure@?pass_text; forward;@t\2@>
  6543. procedure@?start_input; forward;@t\2@>
  6544. procedure@?conditional; forward;@t\2@>
  6545. procedure@?get_x_token; forward;@t\2@>
  6546. procedure@?conv_toks; forward;@t\2@>
  6547. procedure@?ins_the_toks; forward;@t\2@>
  6548. procedure expand;
  6549. var t:halfword; {token that is being ``expanded after''}
  6550. @!p,@!q,@!r:pointer; {for list manipulation}
  6551. @!j:0..buf_size; {index into |buffer|}
  6552. @!cv_backup:integer; {to save the global quantity |cur_val|}
  6553. @!cvl_backup,@!radix_backup,@!co_backup:small_number;
  6554.   {to save |cur_val_level|, etc.}
  6555. @!backup_backup:pointer; {to save |link(backup_head)|}
  6556. @!save_scanner_status:small_number; {temporary storage of |scanner_status|}
  6557. begin cv_backup:=cur_val; cvl_backup:=cur_val_level; radix_backup:=radix;
  6558. co_backup:=cur_order; backup_backup:=link(backup_head);
  6559. if cur_cmd<call then @<Expand a nonmacro@>
  6560. else if cur_cmd<end_template then macro_call
  6561. else @<Insert a token containing |frozen_endv|@>;
  6562. cur_val:=cv_backup; cur_val_level:=cvl_backup; radix:=radix_backup;
  6563. cur_order:=co_backup; link(backup_head):=backup_backup;
  6564. @ @<Expand a nonmacro@>=
  6565. begin if tracing_commands>1 then show_cur_cmd_chr;
  6566. case cur_cmd of
  6567. top_bot_mark:@<Insert the \(a)appropriate mark text into the scanner@>;
  6568. expand_after:@<Expand the token after the next token@>;
  6569. no_expand:@<Suppress expansion of the next token@>;
  6570. cs_name:@<Manufacture a control sequence name@>;
  6571. convert:conv_toks; {this procedure is discussed in Part 27 below}
  6572. the:ins_the_toks; {this procedure is discussed in Part 27 below}
  6573. if_test:conditional; {this procedure is discussed in Part 28 below}
  6574. fi_or_else:@<Terminate the current conditional and skip to \.{\\fi}@>;
  6575. input:@<Initiate or terminate input from a file@>;
  6576. othercases @<Complain about an undefined macro@>
  6577. endcases;
  6578. @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
  6579. @<Expand the token after...@>=
  6580. begin get_token; t:=cur_tok; get_token;
  6581. if cur_cmd>max_command then expand@+else back_input;
  6582. cur_tok:=t; back_input;
  6583. @ The implementation of \.{\\noexpand} is a bit trickier, because it is
  6584. necessary to insert a special `|dont_expand|' marker into \TeX's reading
  6585. mechanism.  This special marker is processed by |get_next|, but it does
  6586. not slow down the inner loop.
  6587. Since \.{\\outer} macros might arise here, we must also
  6588. clear the |scanner_status| temporarily.
  6589. @<Suppress expansion...@>=
  6590. begin save_scanner_status:=scanner_status; scanner_status:=normal;
  6591. get_token; scanner_status:=save_scanner_status; t:=cur_tok;
  6592. back_input; {now |start| and |loc| point to the backed-up token |t|}
  6593. if t>=cs_token_flag then
  6594.   begin p:=get_avail; info(p):=cs_token_flag+frozen_dont_expand;
  6595.   link(p):=loc; start:=p; loc:=p;
  6596.   end;
  6597. @ @<Complain about an undefined macro@>=
  6598. begin print_err("Undefined control sequence");
  6599. @.Undefined control sequence@>
  6600. help5("The control sequence at the end of the top line")@/
  6601. ("of your error message was never \def'ed. If you have")@/
  6602. ("misspelled it (e.g., `\hobx'), type `I' and the correct")@/
  6603. ("spelling (e.g., `I\hbox'). Otherwise just continue,")@/
  6604. ("and I'll forget about whatever was undefined.");
  6605. error;
  6606. @ The |expand| procedure and some other routines that construct token
  6607. lists find it convenient to use the following macros, which are valid only if
  6608. the variables |p| and |q| are reserved for token-list building.
  6609. @d store_new_token(#)==begin q:=get_avail; link(p):=q; info(q):=#;
  6610.   p:=q; {|link(p)| is |null|}
  6611.   end
  6612. @d fast_store_new_token(#)==begin fast_get_avail(q); link(p):=q; info(q):=#;
  6613.   p:=q; {|link(p)| is |null|}
  6614.   end
  6615. @ @<Manufacture a control...@>=
  6616. begin r:=get_avail; p:=r; {head of the list of characters}
  6617. repeat get_x_token;
  6618. if cur_cs=0 then store_new_token(cur_tok);
  6619. until cur_cs<>0;
  6620. if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
  6621. @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
  6622. flush_list(r);
  6623. if eq_type(cur_cs)=undefined_cs then
  6624.   begin eq_define(cur_cs,relax,256); {N.B.: The |save_stack| might change}
  6625.   end; {the control sequence will now match `\.{\\relax}'}
  6626. cur_tok:=cur_cs+cs_token_flag; back_input;
  6627. @ @<Complain about missing \.{\\endcsname}@>=
  6628. begin print_err("Missing "); print_esc("endcsname"); print(" inserted");
  6629. @.Missing \\endcsname...@>
  6630. help2("The control sequence marked <to be read again> should")@/
  6631.   ("not appear between \csname and \endcsname.");
  6632. back_error;
  6633. @ @<Look up the characters of list |r| in the hash table...@>=
  6634. j:=first; p:=link(r);
  6635. while p<>null do
  6636.   begin if j>=max_buf_stack then
  6637.     begin max_buf_stack:=j+1;
  6638.     if max_buf_stack=buf_size then
  6639.       overflow("buffer size",buf_size);
  6640. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  6641.     end;
  6642.   buffer[j]:=info(p) mod @'400; incr(j); p:=link(p);
  6643.   end;
  6644. if j>first+1 then
  6645.   begin no_new_control_sequence:=false; cur_cs:=id_lookup(first,j-first);
  6646.   no_new_control_sequence:=true;
  6647.   end
  6648. else if j=first then cur_cs:=null_cs {the list is empty}
  6649. else cur_cs:=single_base+buffer[first] {the list has length one}
  6650. @ An |end_template| command is effectively changed to an |endv| command
  6651. by the following code. (The reason for this is discussed below; the
  6652. |frozen_end_template| at the end of the template has passed the
  6653. |check_outer_validity| test, so its mission of error detection has been
  6654. accomplished.)
  6655. @<Insert a token containing |frozen_endv|@>=
  6656. begin cur_tok:=cs_token_flag+frozen_endv; back_input;
  6657. @ The processing of \.{\\input} involves the |start_input| subroutine,
  6658. which will be declared later; the processing of \.{\\endinput} is trivial.
  6659. @<Put each...@>=
  6660. primitive("input",input,0);@/
  6661. @!@:input_}{\.{\\input} primitive@>
  6662. primitive("endinput",input,1);@/
  6663. @!@:end_input_}{\.{\\endinput} primitive@>
  6664. @ @<Cases of |print_cmd_chr|...@>=
  6665. input: if chr_code=0 then print_esc("input")@+else print_esc("endinput");
  6666. @ @<Initiate or terminate input...@>=
  6667. if cur_chr>0 then force_eof:=true
  6668. else if name_in_progress then insert_relax
  6669. else start_input
  6670. @ Sometimes the expansion looks too far ahead, so we want to insert
  6671. a harmless \.{\\relax} into the user's input.
  6672. @<Declare the procedure called |insert_relax|@>=
  6673. procedure insert_relax;
  6674. begin cur_tok:=cs_token_flag+cur_cs; back_input;
  6675. cur_tok:=cs_token_flag+frozen_relax; back_input; token_type:=inserted;
  6676. @ Here is a recursive procedure that is \TeX's usual way to get the
  6677. next token of input. It has been slightly optimized to take account of
  6678. common cases.
  6679. @p procedure get_x_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
  6680.   and expands macros}
  6681. label restart,done;
  6682. begin restart: get_next;
  6683. @^inner loop@>
  6684. if cur_cmd<=max_command then goto done;
  6685. if cur_cmd>=call then
  6686.   if cur_cmd<end_template then macro_call
  6687.   else  begin cur_cs:=frozen_endv; cur_cmd:=endv;
  6688.     goto done; {|cur_chr=null_list|}
  6689.     end
  6690. else expand;
  6691. goto restart;
  6692. done: if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6693. else cur_tok:=cs_token_flag+cur_cs;
  6694. @ The |get_x_token| procedure is equivalent to two consecutive
  6695. procedure calls: |get_next; x_token|.
  6696. @p procedure x_token; {|get_x_token| without the initial |get_next|}
  6697. begin while cur_cmd>max_command do
  6698.   begin expand;
  6699.   get_next;
  6700.   end;
  6701. if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6702. else cur_tok:=cs_token_flag+cur_cs;
  6703. @ A control sequence that has been \.{\\def}'ed by the user is expanded by
  6704. \TeX's |macro_call| procedure.
  6705. Before we get into the details of |macro_call|, however, let's consider the
  6706. treatment of primitives like \.{\\topmark}, since they are essentially
  6707. macros without parameters. The token lists for such marks are kept in a
  6708. global array of five pointers; we refer to the individual entries of this
  6709. array by symbolic names |top_mark|, etc. The value of |top_mark| is either
  6710. |null| or a pointer to the reference count of a token list.
  6711. @d top_mark_code=0 {the mark in effect at the previous page break}
  6712. @d first_mark_code=1 {the first mark between |top_mark| and |bot_mark|}
  6713. @d bot_mark_code=2 {the mark in effect at the current page break}
  6714. @d split_first_mark_code=3 {the first mark found by \.{\\vsplit}}
  6715. @d split_bot_mark_code=4 {the last mark found by \.{\\vsplit}}
  6716. @d top_mark==cur_mark[top_mark_code]
  6717. @d first_mark==cur_mark[first_mark_code]
  6718. @d bot_mark==cur_mark[bot_mark_code]
  6719. @d split_first_mark==cur_mark[split_first_mark_code]
  6720. @d split_bot_mark==cur_mark[split_bot_mark_code]
  6721. @<Glob...@>=
  6722. @!cur_mark:array[top_mark_code..split_bot_mark_code] of pointer;
  6723.   {token lists for marks}
  6724. @ @<Set init...@>=
  6725. top_mark:=null; first_mark:=null; bot_mark:=null;
  6726. split_first_mark:=null; split_bot_mark:=null;
  6727. @ @<Put each...@>=
  6728. primitive("topmark",top_bot_mark,top_mark_code);
  6729. @!@:top_mark_}{\.{\\topmark} primitive@>
  6730. primitive("firstmark",top_bot_mark,first_mark_code);
  6731. @!@:first_mark_}{\.{\\firstmark} primitive@>
  6732. primitive("botmark",top_bot_mark,bot_mark_code);
  6733. @!@:bot_mark_}{\.{\\botmark} primitive@>
  6734. primitive("splitfirstmark",top_bot_mark,split_first_mark_code);
  6735. @!@:split_first_mark_}{\.{\\splitfirstmark} primitive@>
  6736. primitive("splitbotmark",top_bot_mark,split_bot_mark_code);
  6737. @!@:split_bot_mark_}{\.{\\splitbotmark} primitive@>
  6738. @ @<Cases of |print_cmd_chr|...@>=
  6739. top_bot_mark: case chr_code of
  6740.   first_mark_code: print_esc("firstmark");
  6741.   bot_mark_code: print_esc("botmark");
  6742.   split_first_mark_code: print_esc("splitfirstmark");
  6743.   split_bot_mark_code: print_esc("splitbotmark");
  6744.   othercases print_esc("topmark")
  6745.   endcases;
  6746. @ The following code is activated when |cur_cmd=top_bot_mark| and
  6747. when |cur_chr| is a code like |top_mark_code|.
  6748. @<Insert the \(a)appropriate mark text into the scanner@>=
  6749. begin if cur_mark[cur_chr]<>null then
  6750.   begin_token_list(cur_mark[cur_chr],mark_text);
  6751. @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
  6752. scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
  6753. |outer_call|, or |long_outer_call|.  The control sequence definition
  6754. appears in the token list whose reference count is in location |cur_chr|
  6755. of |mem|.
  6756. The global variable |long_state| will be set to |call| or to |long_call|,
  6757. depending on whether or not the control sequence disallows \.{\\par}
  6758. in its parameters. The |get_next| routine will set |long_state| to
  6759. |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
  6760. control sequence occurs in the midst of an argument.
  6761. @<Glob...@>=
  6762. @!long_state:call..long_outer_call; {governs the acceptance of \.{\\par}}
  6763. @ The parameters, if any, must be scanned before the macro is expanded.
  6764. Parameters are token lists without reference counts. They are placed on
  6765. an auxiliary stack called |pstack| while they are being scanned, since
  6766. the |param_stack| may be losing entries during the matching process.
  6767. (Note that |param_stack| can't be gaining entries, since |macro_call| is
  6768. the only routine that puts anything onto |param_stack|, and it
  6769. is not recursive.)
  6770. @<Glob...@>=
  6771. @!pstack:array[0..8] of pointer; {arguments supplied to a macro}
  6772. @ After parameter scanning is complete, the parameters are moved to the
  6773. |param_stack|. Then the macro body is fed to the scanner; in other words,
  6774. |macro_call| places the defined text of the control sequence at the
  6775. top of\/ \TeX's input stack, so that |get_next| will proceed to read it
  6776. next.
  6777. The global variable |cur_cs| contains the |eqtb| address of the control sequence
  6778. being expanded, when |macro_call| begins. If this control sequence has not been
  6779. declared \.{\\long}, i.e., if its command code in the |eq_type| field is
  6780. not |long_call| or |long_outer_call|, its parameters are not allowed to contain
  6781. the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
  6782. call is aborted, and the \.{\\par} will be rescanned.
  6783. @<Declare the procedure called |macro_call|@>=
  6784. procedure macro_call; {invokes a user-defined control sequence}
  6785. label exit, continue, done, done1, found;
  6786. var r:pointer; {current node in the macro's token list}
  6787. @!p:pointer; {current node in parameter token list being built}
  6788. @!q:pointer; {new node being put into the token list}
  6789. @!s:pointer; {backup pointer for parameter matching}
  6790. @!t:pointer; {cycle pointer for backup recovery}
  6791. @!u,@!v:pointer; {auxiliary pointers for backup recovery}
  6792. @!rbrace_ptr:pointer; {one step before the last |right_brace| token}
  6793. @!n:small_number; {the number of parameters scanned}
  6794. @!unbalance:halfword; {unmatched left braces in current parameter}
  6795. @!m:halfword; {the number of tokens or groups (usually)}
  6796. @!ref_count:pointer; {start of the token list}
  6797. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  6798. @!save_warning_index:pointer; {|warning_index| upon entry}
  6799. @!match_chr:ASCII_code; {character used in parameter}
  6800. begin save_scanner_status:=scanner_status; save_warning_index:=warning_index;
  6801. warning_index:=cur_cs; ref_count:=cur_chr; r:=link(ref_count); n:=0;
  6802. if tracing_macros>0 then @<Show the text of the macro being expanded@>;
  6803. if info(r)<>end_match_token then
  6804.   @<Scan the parameters and make |link(r)| point to the macro body; but
  6805.     |return| if an illegal \.{\\par} is detected@>;
  6806. @<Feed the macro body and its parameters to the scanner@>;
  6807. exit:scanner_status:=save_scanner_status; warning_index:=save_warning_index;
  6808. @ Before we put a new token list on the input stack, it is wise to clean off
  6809. all token lists that have recently been depleted. Then a user macro that ends
  6810. with a call to itself will not require unbounded stack space.
  6811. @<Feed the macro body and its parameters to the scanner@>=
  6812. while (state=token_list)and(loc=null) do end_token_list; {conserve stack space}
  6813. begin_token_list(ref_count,macro); name:=warning_index; loc:=link(r);
  6814. if n>0 then
  6815.   begin if param_ptr+n>max_param_stack then
  6816.     begin max_param_stack:=param_ptr+n;
  6817.     if max_param_stack>param_size then
  6818.       overflow("parameter stack size",param_size);
  6819. @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
  6820.     end;
  6821.   for m:=0 to n-1 do param_stack[param_ptr+m]:=pstack[m];
  6822.   param_ptr:=param_ptr+n;
  6823.   end
  6824. @ At this point, the reader will find it advisable to review the explanation
  6825. of token list format that was presented earlier, since many aspects of that
  6826. format are of importance chiefly in the |macro_call| routine.
  6827. The token list might begin with a string of compulsory tokens before the
  6828. first |match| or |end_match|. In that case the macro name is supposed to be
  6829. followed by those tokens; the following program will set |s=null| to
  6830. represent this restriction. Otherwise |s| will be set to the first token of
  6831. a string that will delimit the next parameter.
  6832. @<Scan the parameters and make |link(r)| point to the macro body...@>=
  6833. begin scanner_status:=matching; unbalance:=0;
  6834. long_state:=eq_type(cur_cs);
  6835. if long_state>=outer_call then long_state:=long_state-2;
  6836. repeat link(temp_head):=null;
  6837. if (info(r)>match_token+255)or(info(r)<match_token) then s:=null
  6838. else  begin match_chr:=info(r)-match_token; s:=link(r); r:=s;
  6839.   p:=temp_head; m:=0;
  6840.   end;
  6841. @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
  6842.   simply scan the delimiter string@>;@/
  6843. {now |info(r)| is a token whose command code is either |match| or |end_match|}
  6844. until info(r)=end_match_token;
  6845. @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
  6846. any token found by |get_token|. Therefore an undelimited parameter---i.e.,
  6847. a |match| that is immediately followed by |match| or |end_match|---will
  6848. always fail the test `|cur_tok=info(r)|' in the following algorithm.
  6849. @<Scan a parameter until its delimiter string has been found; or, ...@>=
  6850. continue: get_token; {set |cur_tok| to the next token of input}
  6851. if cur_tok=info(r) then
  6852.   @<Advance \(r)|r|; |goto found| if the parameter delimiter has been
  6853.     fully matched, otherwise |goto continue|@>;
  6854. @<Contribute the recently matched tokens to the current parameter, and
  6855.   |goto continue| if a partial match is still in effect;
  6856.   but abort if |s=null|@>;
  6857. if cur_tok=par_token then if long_state<>long_call then
  6858.   @<Report a runaway argument and abort@>;
  6859. if cur_tok<right_brace_limit then
  6860.   if cur_tok<left_brace_limit then
  6861.     @<Contribute an entire group to the current parameter@>
  6862.   else @<Report an extra right brace and |goto continue|@>
  6863. else @<Store the current token, but |goto continue| if it is
  6864.    a blank space that would become an undelimited parameter@>;
  6865. incr(m);
  6866. if info(r)>end_match_token then goto continue;
  6867. if info(r)<match_token then goto continue;
  6868. found: if s<>null then @<Tidy up the parameter just scanned, and tuck it away@>
  6869. @ @<Store the current token, but |goto continue| if it is...@>=
  6870. begin if cur_tok=space_token then
  6871.   if info(r)<=end_match_token then
  6872.     if info(r)>=match_token then goto continue;
  6873. store_new_token(cur_tok);
  6874. @ A slightly subtle point arises here: When the parameter delimiter ends
  6875. with `\.{\#\{}', the token list will have a left brace both before and
  6876. after the |end_match|\kern-.4pt. Only one of these should affect the
  6877. |align_state|, but both will be scanned, so we must make a correction.
  6878. @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
  6879. begin r:=link(r);
  6880. if (info(r)>=match_token)and(info(r)<=end_match_token) then
  6881.   begin if cur_tok<left_brace_limit then decr(align_state);
  6882.   goto found;
  6883.   end
  6884. else goto continue;
  6885. @ @<Report an extra right brace and |goto continue|@>=
  6886. begin back_input; print_err("Argument of "); sprint_cs(warning_index);
  6887. @.Argument of \\x has...@>
  6888. print(" has an extra }");
  6889. help6("I've run across a `}' that doesn't seem to match anything.")@/
  6890.   ("For example, `\def\a#1{...}' and `\a}' would produce")@/
  6891.   ("this error. If you simply proceed now, the `\par' that")@/
  6892.   ("I've just inserted will cause me to report a runaway")@/
  6893.   ("argument that might be the root of the problem. But if")@/
  6894.   ("your `}' was spurious, just type `2' and it will go away.");
  6895. incr(align_state); long_state:=call; cur_tok:=par_token; ins_error;
  6896. end {a white lie; the \.{\\par} won't always trigger a runaway}
  6897. @ If |long_state=outer_call|, a runaway argument has already been reported.
  6898. @<Report a runaway argument and abort@>=
  6899. begin if long_state=call then
  6900.   begin runaway; print_err("Paragraph ended before ");
  6901. @.Paragraph ended before...@>
  6902.   sprint_cs(warning_index); print(" was complete");
  6903.   help3("I suspect you've forgotten a `}', causing me to apply this")@/
  6904.     ("control sequence to too much text. How can we recover?")@/
  6905.     ("My plan is to forget the whole thing and hope for the best.");
  6906.   back_error;
  6907.   end;
  6908. pstack[n]:=link(temp_head); align_state:=align_state-unbalance;
  6909. for m:=0 to n do flush_list(pstack[m]);
  6910. return;
  6911. @ When the following code becomes active, we have matched tokens from |s| to
  6912. the predecessor of |r|, and we have found that |cur_tok<>info(r)|. An
  6913. interesting situation now presents itself: If the parameter is to be
  6914. delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
  6915. we want to contribute one `\.a' to the current parameter and resume
  6916. looking for a `\.b'. The program must account for such partial matches and
  6917. for others that can be quite complex.  But most of the time we have |s=r|
  6918. and nothing needs to be done.
  6919. Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
  6920. parameters of non-\.{\\long} macros. For example, consider a case like
  6921. `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
  6922. by an exclamation point. In such situations it does not seem appropriate
  6923. to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
  6924. the rules.
  6925. @<Contribute the recently matched tokens to the current parameter...@>=
  6926. if s<>r then
  6927.   if s=null then @<Report an improper use of the macro and abort@>
  6928.   else  begin t:=s;
  6929.     repeat store_new_token(info(t)); incr(m); u:=link(t); v:=s;
  6930.     loop@+  begin if u=r then
  6931.         if cur_tok<>info(v) then goto done
  6932.         else  begin r:=link(v); goto continue;
  6933.           end;
  6934.       if info(u)<>info(v) then goto done;
  6935.       u:=link(u); v:=link(v);
  6936.       end;
  6937.     done: t:=link(t);
  6938.     until t=r;
  6939.     r:=s; {at this point, no tokens are recently matched}
  6940.     end
  6941. @ @<Report an improper use...@>=
  6942. begin print_err("Use of "); sprint_cs(warning_index);
  6943. @.Use of x doesn't match...@>
  6944. print(" doesn't match its definition");
  6945. help4("If you say, e.g., `\def\a1{...}', then you must always")@/
  6946.   ("put `1' after `\a', since control sequence names are")@/
  6947.   ("made up of letters only. The macro here has not been")@/
  6948.   ("followed by the required stuff, so I'm ignoring it.");
  6949. error; return;
  6950. @ @<Contribute an entire group to the current parameter@>=
  6951. begin unbalance:=1;
  6952. @^inner loop@>
  6953. loop@+  begin fast_store_new_token(cur_tok); get_token;
  6954.   if cur_tok=par_token then if long_state<>long_call then
  6955.     @<Report a runaway argument and abort@>;
  6956.   if cur_tok<right_brace_limit then
  6957.     if cur_tok<left_brace_limit then incr(unbalance)
  6958.     else  begin decr(unbalance);
  6959.       if unbalance=0 then goto done1;
  6960.       end;
  6961.   end;
  6962. done1: rbrace_ptr:=p; store_new_token(cur_tok);
  6963. @ If the parameter consists of a single group enclosed in braces, we must
  6964. strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
  6965. @<Tidy up the parameter just scanned, and tuck it away@>=
  6966. begin if (m=1)and(info(p)<right_brace_limit)and(p<>temp_head) then
  6967.   begin link(rbrace_ptr):=null; free_avail(p);
  6968.   p:=link(temp_head); pstack[n]:=link(p); free_avail(p);
  6969.   end
  6970. else pstack[n]:=link(temp_head);
  6971. incr(n);
  6972. if tracing_macros>0 then
  6973.   begin begin_diagnostic; print_nl(match_chr); print_int(n);
  6974.   print("<-"); show_token_list(pstack[n-1],null,1000);
  6975.   end_diagnostic(false);
  6976.   end;
  6977. @ @<Show the text of the macro being expanded@>=
  6978. begin begin_diagnostic; print_ln; print_cs(warning_index);
  6979. token_show(ref_count); end_diagnostic(false);
  6980. @* \[26] Basic scanning subroutines.
  6981. Let's turn now to some procedures that \TeX\ calls upon frequently to digest
  6982. certain kinds of patterns in the input. Most of these are quite simple;
  6983. some are quite elaborate. Almost all of the routines call |get_x_token|,
  6984. which can cause them to be invoked recursively.
  6985. @^stomach@>
  6986. @^recursion@>
  6987. @ The |scan_left_brace| routine is called when a left brace is supposed to be
  6988. the next non-blank token. (The term ``left brace'' means, more precisely,
  6989. a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
  6990. appear before the |left_brace|.
  6991. @p procedure scan_left_brace; {reads a mandatory |left_brace|}
  6992. begin @<Get the next non-blank non-relax non-call token@>;
  6993. if cur_cmd<>left_brace then
  6994.   begin print_err("Missing { inserted");
  6995. @.Missing \{ inserted@>
  6996.   help4("A left brace was mandatory here, so I've put one in.")@/
  6997.     ("You might want to delete and/or insert some corrections")@/
  6998.     ("so that I will find a matching right brace soon.")@/
  6999.     ("(If you're confused by all this, try typing `I}' now.)");
  7000.   back_error; cur_tok:=left_brace_token+"{"; cur_cmd:=left_brace;
  7001.   cur_chr:="{"; incr(align_state);
  7002.   end;
  7003. @ @<Get the next non-blank non-relax non-call token@>=
  7004. repeat get_x_token;
  7005. until (cur_cmd<>spacer)and(cur_cmd<>relax)
  7006. @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
  7007. by optional spaces; `\.{\\relax}' is not ignored here.
  7008. @p procedure scan_optional_equals;
  7009. begin  @<Get the next non-blank non-call token@>;
  7010. if cur_tok<>other_token+"=" then back_input;
  7011. @ @<Get the next non-blank non-call token@>=
  7012. repeat get_x_token;
  7013. until cur_cmd<>spacer
  7014. @ In case you are getting bored, here is a slightly less trivial routine:
  7015. Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
  7016. `\.{width}', the |scan_keyword| routine checks to see whether the next
  7017. tokens of input match this string. The match must be exact, except that
  7018. uppercase letters will match their lowercase counterparts; uppercase
  7019. equivalents are determined by subtracting |"a"-"A"|, rather than using the
  7020. |uc_code| table, since \TeX\ uses this routine only for its own limited
  7021. set of keywords.
  7022. If a match is found, the characters are effectively removed from the input
  7023. and |true| is returned. Otherwise |false| is returned, and the input
  7024. is left essentially unchanged (except for the fact that some macros
  7025. may have been expanded, etc.).
  7026. @^inner loop@>
  7027. @p function scan_keyword(@!s:str_number):boolean; {look for a given string}
  7028. label exit;
  7029. var p:pointer; {tail of the backup list}
  7030. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7031. @!k:pool_pointer; {index into |str_pool|}
  7032. begin p:=backup_head; link(p):=null; k:=str_start[s];
  7033. while k<str_start[s+1] do
  7034.   begin get_x_token; {recursion is possible here}
  7035. @^recursion@>
  7036.   if (cur_cs=0)and@|
  7037.    ((cur_chr=so(str_pool[k]))or(cur_chr=so(str_pool[k])-"a"+"A")) then
  7038.     begin store_new_token(cur_tok); incr(k);
  7039.     end
  7040.   else if (cur_cmd<>spacer)or(p<>backup_head) then
  7041.     begin back_input;
  7042.     if p<>backup_head then back_list(link(backup_head));
  7043.     scan_keyword:=false; return;
  7044.     end;
  7045.   end;
  7046. flush_list(link(backup_head)); scan_keyword:=true;
  7047. exit:end;
  7048. @ Here is a procedure that sounds an alarm when mu and non-mu units
  7049. are being switched.
  7050. @p procedure mu_error;
  7051. begin print_err("Incompatible glue units");
  7052. @.Incompatible glue units@>
  7053. help1("I'm going to assume that 1mu=1pt when they're mixed.");
  7054. error;
  7055. @ The next routine `|scan_something_internal|' is used to fetch internal
  7056. numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
  7057. when expanding constructions like `\.{\\the\\toks0}' and
  7058. `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
  7059. procedure, which calls |scan_something_internal|; on the other hand,
  7060. |scan_something_internal| also calls |scan_int|, for constructions like
  7061. `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
  7062. have to declare |scan_int| as a |forward| procedure. A few other
  7063. procedures are also declared at this point.
  7064. @p procedure@?scan_int; forward; {scans an integer value}
  7065. @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
  7066. @t\4\4@>@<Declare procedures that scan font-related stuff@>
  7067. @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
  7068. begins.  For example, an integer or dimension or glue value could occur
  7069. immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
  7070. respect to token lists in constructions like
  7071. `\.{\\xdef\\o\{\\the\\output\}}'.  On the other hand, only integers are
  7072. allowed after a construction like `\.{\\count}'. To handle the various
  7073. possibilities, |scan_something_internal| has a |level| parameter, which
  7074. tells the ``highest'' kind of quantity that |scan_something_internal| is
  7075. allowed to produce. Six levels are distinguished, namely |int_val|,
  7076. |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
  7077. The output of |scan_something_internal| (and of the other routines
  7078. |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
  7079. variable |cur_val|, and its level is put into |cur_val_level|. The highest
  7080. values of |cur_val_level| are special: |mu_val| is used only when
  7081. |cur_val| points to something in a ``muskip'' register, or to one of the
  7082. three parameters \.{\\thinmuskip}, \.{\\midmuskip}, \.{\\thickmuskip};
  7083. |ident_val| is used only when |cur_val| points to a font identifier;
  7084. |tok_val| is used only when |cur_val| points to |null| or to the reference
  7085. count of a token list. The last two cases are allowed only when
  7086. |scan_something_internal| is called with |level=tok_val|.
  7087. If the output is glue, |cur_val| will point to a glue specification, and
  7088. the reference count of that glue will have been updated to reflect this
  7089. reference; if the output is a nonempty token list, |cur_val| will point to
  7090. its reference count, but in this case the count will not have been updated.
  7091. Otherwise |cur_val| will contain the integer or scaled value in question.
  7092. @d int_val=0 {integer values}
  7093. @d dimen_val=1 {dimension values}
  7094. @d glue_val=2 {glue specifications}
  7095. @d mu_val=3 {math glue specifications}
  7096. @d ident_val=4 {font identifier}
  7097. @d tok_val=5 {token lists}
  7098. @<Glob...@>=
  7099. @!cur_val:integer; {value returned by numeric scanners}
  7100. @!cur_val_level:int_val..tok_val; {the ``level'' of this value}
  7101. @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
  7102. and `\.{\\muskip}' all having |register| as their command code; they are
  7103. distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
  7104. |glue_val|, or |mu_val|.
  7105. @<Put each...@>=
  7106. primitive("count",register,int_val);
  7107. @!@:count_}{\.{\\count} primitive@>
  7108. primitive("dimen",register,dimen_val);
  7109. @!@:dimen_}{\.{\\dimen} primitive@>
  7110. primitive("skip",register,glue_val);
  7111. @!@:skip_}{\.{\\skip} primitive@>
  7112. primitive("muskip",register,mu_val);
  7113. @!@:mu_skip_}{\.{\\muskip} primitive@>
  7114. @ @<Cases of |print_cmd_chr|...@>=
  7115. register: if chr_code=int_val then print_esc("count")
  7116.   else if chr_code=dimen_val then print_esc("dimen")
  7117.   else if chr_code=glue_val then print_esc("skip")
  7118.   else print_esc("muskip");
  7119. @ OK, we're ready for |scan_something_internal| itself. A second parameter,
  7120. |negative|, is set |true| if the value that is found should be negated.
  7121. It is assumed that |cur_cmd| and |cur_chr| represent the first token of
  7122. the internal quantity to be scanned; an error will be signalled if
  7123. |cur_cmd<min_internal| or |cur_cmd>max_internal|.
  7124. @d scanned_result_end(#)==cur_val_level:=#;@+end
  7125. @d scanned_result(#)==@+begin cur_val:=#;scanned_result_end
  7126. @p procedure scan_something_internal(@!level:small_number;@!negative:boolean);
  7127.   {fetch an internal parameter}
  7128. var m:halfword; {|chr_code| part of the operand token}
  7129. @!p:0..nest_size; {index into |nest|}
  7130. begin m:=cur_chr;
  7131. case cur_cmd of
  7132. def_code: @<Fetch a character code from some table@>;
  7133. toks_register,assign_toks,def_family,set_font,def_font: @<Fetch a token list or
  7134.   font identifier, provided that |level=tok_val|@>;
  7135. assign_int: scanned_result(eqtb[m].int)(int_val);
  7136. assign_dimen: scanned_result(eqtb[m].sc)(dimen_val);
  7137. assign_glue: scanned_result(equiv(m))(glue_val);
  7138. assign_mu_glue: scanned_result(equiv(m))(mu_val);
  7139. set_aux: @<Fetch the |space_factor| or the |prev_depth|@>;
  7140. set_prev_graf: @<Fetch the |prev_graf|@>;
  7141. set_page_int:@<Fetch the |dead_cycles| or the |insert_penalties|@>;
  7142. set_page_dimen: @<Fetch something on the |page_so_far|@>;
  7143. set_shape: @<Fetch the |par_shape| size@>;
  7144. set_box_dimen: @<Fetch a box dimension@>;
  7145. char_given,math_given: scanned_result(cur_chr)(int_val);
  7146. assign_font_dimen: @<Fetch a font dimension@>;
  7147. assign_font_int: @<Fetch a font integer@>;
  7148. register: @<Fetch a register@>;
  7149. last_item: @<Fetch an item in the current node, if appropriate@>;
  7150. othercases @<Complain that \.{\\the} can't do this; give zero result@>
  7151. endcases;@/
  7152. while cur_val_level>level do @<Convert \(c)|cur_val| to a lower level@>;
  7153. @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
  7154. @ @<Fetch a character code from some table@>=
  7155. begin scan_char_num;
  7156. if m=math_code_base then scanned_result(ho(math_code(cur_val)))(int_val)
  7157. else if m<math_code_base then scanned_result(equiv(m+cur_val))(int_val)
  7158. else scanned_result(eqtb[m+cur_val].int)(int_val);
  7159. @ @<Fetch a token list...@>=
  7160. if level<>tok_val then
  7161.   begin print_err("Missing number, treated as zero");
  7162. @.Missing number...@>
  7163.   help3("A number should have been here; I inserted `0'.")@/
  7164.     ("(If you can't figure out why I needed to see a number,")@/
  7165.     ("look up `weird error' in the index to The TeXbook.)");
  7166. @:TeXbook}{\sl The \TeX book@>
  7167.   back_error; scanned_result(0)(dimen_val);
  7168.   end
  7169. else if cur_cmd<=assign_toks then
  7170.   begin if cur_cmd<assign_toks then {|cur_cmd=toks_register|}
  7171.     begin scan_eight_bit_int; m:=toks_base+cur_val;
  7172.     end;
  7173.   scanned_result(equiv(m))(tok_val);
  7174.   end
  7175. else  begin back_input; scan_font_ident;
  7176.   scanned_result(font_id_base+cur_val)(ident_val);
  7177.   end
  7178. @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
  7179. mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
  7180. associated mode in the modifier part of the |set_aux| command.
  7181. The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
  7182. `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
  7183. modified by either |width_offset|, |height_offset|, or |depth_offset|.
  7184. And the |last_item| command is modified by either |int_val|, |dimen_val|,
  7185. |glue_val|, |input_line_no_code|, or |badness_code|.
  7186. @d input_line_no_code=glue_val+1 {code for \.{\\inputlineno}}
  7187. @d badness_code=glue_val+2 {code for \.{\\badness}}
  7188. @<Put each...@>=
  7189. primitive("spacefactor",set_aux,hmode);
  7190. @!@:space_factor_}{\.{\\spacefactor} primitive@>
  7191. primitive("prevdepth",set_aux,vmode);@/
  7192. @!@:prev_depth_}{\.{\\prevdepth} primitive@>
  7193. primitive("deadcycles",set_page_int,0);
  7194. @!@:dead_cycles_}{\.{\\deadcycles} primitive@>
  7195. primitive("insertpenalties",set_page_int,1);
  7196. @!@:insert_penalties_}{\.{\\insertpenalties} primitive@>
  7197. primitive("wd",set_box_dimen,width_offset);
  7198. @!@:wd_}{\.{\\wd} primitive@>
  7199. primitive("ht",set_box_dimen,height_offset);
  7200. @!@:ht_}{\.{\\ht} primitive@>
  7201. primitive("dp",set_box_dimen,depth_offset);
  7202. @!@:dp_}{\.{\\dp} primitive@>
  7203. primitive("lastpenalty",last_item,int_val);
  7204. @!@:last_penalty_}{\.{\\lastpenalty} primitive@>
  7205. primitive("lastkern",last_item,dimen_val);
  7206. @!@:last_kern_}{\.{\\lastkern} primitive@>
  7207. primitive("lastskip",last_item,glue_val);
  7208. @!@:last_skip_}{\.{\\lastskip} primitive@>
  7209. primitive("inputlineno",last_item,input_line_no_code);
  7210. @!@:input_line_no_}{\.{\\inputlineno} primitive@>
  7211. primitive("badness",last_item,badness_code);
  7212. @!@:badness_}{\.{\\badness} primitive@>
  7213. @ @<Cases of |print_cmd_chr|...@>=
  7214. set_aux: if chr_code=vmode then print_esc("prevdepth")
  7215. @+else print_esc("spacefactor");
  7216. set_page_int: if chr_code=0 then print_esc("deadcycles")
  7217. @+else print_esc("insertpenalties");
  7218. set_box_dimen: if chr_code=width_offset then print_esc("wd")
  7219. else if chr_code=height_offset then print_esc("ht")
  7220. else print_esc("dp");
  7221. last_item: case chr_code of
  7222.   int_val: print_esc("lastpenalty");
  7223.   dimen_val: print_esc("lastkern");
  7224.   glue_val: print_esc("lastskip");
  7225.   input_line_no_code: print_esc("inputlineno");
  7226.   othercases print_esc("badness")
  7227.   endcases;
  7228. @ @<Fetch the |space_factor| or the |prev_depth|@>=
  7229. if abs(mode)<>m then
  7230.   begin print_err("Improper "); print_cmd_chr(set_aux,m);
  7231. @.Improper \\spacefactor@>
  7232. @.Improper \\prevdepth@>
  7233.   help4("You can refer to \spacefactor only in horizontal mode;")@/
  7234.     ("you can refer to \prevdepth only in vertical mode; and")@/
  7235.     ("neither of these is meaningful inside \write. So")@/
  7236.     ("I'm forgetting what you said and using zero instead.");
  7237.   error;
  7238.   if level<>tok_val then scanned_result(0)(dimen_val)
  7239.   else scanned_result(0)(int_val);
  7240.   end
  7241. else if m=vmode then
  7242.   begin cur_val:=prev_depth; cur_val_level:=dimen_val;
  7243.   end
  7244. else begin cur_val:=space_factor; cur_val_level:=int_val;
  7245.   end
  7246. @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
  7247. begin if m=0 then cur_val:=dead_cycles@+else cur_val:=insert_penalties;
  7248. cur_val_level:=int_val;
  7249. @ @<Fetch a box dimension@>=
  7250. begin scan_eight_bit_int;
  7251. if box(cur_val)=null then cur_val:=0 @+else cur_val:=mem[box(cur_val)+m].sc;
  7252. cur_val_level:=dimen_val;
  7253. @ Inside an \.{\\output} routine, a user may wish to look at the page totals
  7254. that were present at the moment when output was triggered.
  7255. @d max_dimen==@'7777777777 {$2^{30}-1$}
  7256. @<Fetch something on the |page_so_far|@>=
  7257. begin if (page_contents=empty) and (not output_active) then
  7258.   if m=0 then cur_val:=max_dimen@+else cur_val:=0
  7259. else cur_val:=page_so_far[m];
  7260. cur_val_level:=dimen_val;
  7261. @ @<Fetch the |prev_graf|@>=
  7262. if mode=0 then scanned_result(0)(int_val) {|prev_graf=0| within \.{\\write}}
  7263. else begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
  7264.   while abs(nest[p].mode_field)<>vmode do decr(p);
  7265.   scanned_result(nest[p].pg_field)(int_val);
  7266.   end
  7267. @ @<Fetch the |par_shape| size@>=
  7268. begin if par_shape_ptr=null then cur_val:=0
  7269. else cur_val:=info(par_shape_ptr);
  7270. cur_val_level:=int_val;
  7271. @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, and \.{\\lastskip} are
  7272. implemented. The reference count for \.{\\lastskip} will be updated later.
  7273. We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
  7274. legal in similar contexts.
  7275. @<Fetch an item in the current node...@>=
  7276. if cur_chr>glue_val then
  7277.   begin if cur_chr=input_line_no_code then cur_val:=line
  7278.   else cur_val:=last_badness; {|cur_chr=badness_code|}
  7279.   cur_val_level:=int_val;
  7280.   end
  7281. else begin if cur_chr=glue_val then cur_val:=zero_glue@+else cur_val:=0;
  7282.   cur_val_level:=cur_chr;
  7283.   if not is_char_node(tail)and(mode<>0) then
  7284.     case cur_chr of
  7285.     int_val: if type(tail)=penalty_node then cur_val:=penalty(tail);
  7286.     dimen_val: if type(tail)=kern_node then cur_val:=width(tail);
  7287.     glue_val: if type(tail)=glue_node then
  7288.       begin cur_val:=glue_ptr(tail);
  7289.       if subtype(tail)=mu_glue then cur_val_level:=mu_val;
  7290.       end;
  7291.     end {there are no other cases}
  7292.   else if (mode=vmode)and(tail=head) then
  7293.     case cur_chr of
  7294.     int_val: cur_val:=last_penalty;
  7295.     dimen_val: cur_val:=last_kern;
  7296.     glue_val: if last_glue<>max_halfword then cur_val:=last_glue;
  7297.     end; {there are no other cases}
  7298.   end
  7299. @ @<Fetch a font dimension@>=
  7300. begin find_font_dimen(false); font_info[fmem_ptr].sc:=0;
  7301. scanned_result(font_info[cur_val].sc)(dimen_val);
  7302. @ @<Fetch a font integer@>=
  7303. begin scan_font_ident;
  7304. if m=0 then scanned_result(hyphen_char[cur_val])(int_val)
  7305. else scanned_result(skew_char[cur_val])(int_val);
  7306. @ @<Fetch a register@>=
  7307. begin scan_eight_bit_int;
  7308. case m of
  7309. int_val:cur_val:=count(cur_val);
  7310. dimen_val:cur_val:=dimen(cur_val);
  7311. glue_val: cur_val:=skip(cur_val);
  7312. mu_val: cur_val:=mu_skip(cur_val);
  7313. end; {there are no other cases}
  7314. cur_val_level:=m;
  7315. @ @<Complain that \.{\\the} can't do this; give zero result@>=
  7316. begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
  7317. @.You can't use x after ...@>
  7318. print("' after "); print_esc("the");
  7319. help1("I'm forgetting what you said and using zero instead.");
  7320. error;
  7321. if level<>tok_val then scanned_result(0)(dimen_val)
  7322. else scanned_result(0)(int_val);
  7323. @ When a |glue_val| changes to a |dimen_val|, we use the width component
  7324. of the glue; there is no need to decrease the reference count, since it
  7325. has not yet been increased.  When a |dimen_val| changes to an |int_val|,
  7326. we use scaled points so that the value doesn't actually change. And when a
  7327. |mu_val| changes to a |glue_val|, the value doesn't change either.
  7328. @<Convert \(c)|cur_val| to a lower level@>=
  7329. begin if cur_val_level=glue_val then cur_val:=width(cur_val)
  7330. else if cur_val_level=mu_val then mu_error;
  7331. decr(cur_val_level);
  7332. @ If |cur_val| points to a glue specification at this point, the reference
  7333. count for the glue does not yet include the reference by |cur_val|.
  7334. If |negative| is |true|, |cur_val_level| is known to be |<=mu_val|.
  7335. @<Fix the reference count, if any, ...@>=
  7336. if negative then
  7337.   if cur_val_level>=glue_val then
  7338.     begin cur_val:=new_spec(cur_val);
  7339.     @<Negate all three glue components of |cur_val|@>;
  7340.     end
  7341.   else negate(cur_val)
  7342. else if (cur_val_level>=glue_val)and(cur_val_level<=mu_val) then
  7343.   add_glue_ref(cur_val)
  7344. @ @<Negate all three...@>=
  7345. begin negate(width(cur_val));
  7346. negate(stretch(cur_val));
  7347. negate(shrink(cur_val));
  7348. @ Our next goal is to write the |scan_int| procedure, which scans anything that
  7349. \TeX\ treats as an integer. But first we might as well look at some simple
  7350. applications of |scan_int| that have already been made inside of
  7351. |scan_something_internal|.
  7352. @ @<Declare procedures that scan restricted classes of integers@>=
  7353. procedure scan_eight_bit_int;
  7354. begin scan_int;
  7355. if (cur_val<0)or(cur_val>255) then
  7356.   begin print_err("Bad register code");
  7357. @.Bad register code@>
  7358.   help2("A register number must be between 0 and 255.")@/
  7359.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7360.   end;
  7361. @ @<Declare procedures that scan restricted classes of integers@>=
  7362. procedure scan_char_num;
  7363. begin scan_int;
  7364. if (cur_val<0)or(cur_val>255) then
  7365.   begin print_err("Bad character code");
  7366. @.Bad character code@>
  7367.   help2("A character number must be between 0 and 255.")@/
  7368.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7369.   end;
  7370. @ While we're at it, we might as well deal with similar routines that
  7371. will be needed later.
  7372. @<Declare procedures that scan restricted classes of integers@>=
  7373. procedure scan_four_bit_int;
  7374. begin scan_int;
  7375. if (cur_val<0)or(cur_val>15) then
  7376.   begin print_err("Bad number");
  7377. @.Bad number@>
  7378.   help2("Since I expected to read a number between 0 and 15,")@/
  7379.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7380.   end;
  7381. @ @<Declare procedures that scan restricted classes of integers@>=
  7382. procedure scan_fifteen_bit_int;
  7383. begin scan_int;
  7384. if (cur_val<0)or(cur_val>@'77777) then
  7385.   begin print_err("Bad mathchar");
  7386. @.Bad mathchar@>
  7387.   help2("A mathchar number must be between 0 and 32767.")@/
  7388.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7389.   end;
  7390. @ @<Declare procedures that scan restricted classes of integers@>=
  7391. procedure scan_twenty_seven_bit_int;
  7392. begin scan_int;
  7393. if (cur_val<0)or(cur_val>@'777777777) then
  7394.   begin print_err("Bad delimiter code");
  7395. @.Bad delimiter code@>
  7396.   help2("A numeric delimiter code must be between 0 and 2^{27}-1.")@/
  7397.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7398.   end;
  7399. @ An integer number can be preceded by any number of spaces and `\.+' or
  7400. `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
  7401. octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
  7402. (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
  7403. an internal variable. After scanning is complete,
  7404. |cur_val| will contain the answer, which must be at most
  7405. $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
  7406. 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
  7407. otherwise |radix| is set to zero. An optional space follows a constant.
  7408. @d octal_token=other_token+"'" {apostrophe, indicates an octal constant}
  7409. @d hex_token=other_token+"""" {double quote, indicates a hex constant}
  7410. @d alpha_token=other_token+"`" {reverse apostrophe, precedes alpha constants}
  7411. @d point_token=other_token+"." {decimal point}
  7412. @d continental_point_token=other_token+"," {decimal point, Eurostyle}
  7413. @<Glob...@>=
  7414. @!radix:small_number; {|scan_int| sets this to 8, 10, 16, or zero}
  7415. @ We initialize the following global variables just in case |expand|
  7416. comes into action before any of the basic scanning routines has assigned
  7417. them a value.
  7418. @<Set init...@>=
  7419. cur_val:=0; cur_val_level:=int_val; radix:=0; cur_order:=0;
  7420. @ The |scan_int| routine is used also to scan the integer part of a
  7421. fraction; for example, the `\.3' in `\.{3.14159}' will be found by
  7422. |scan_int|. The |scan_dimen| routine assumes that |cur_tok=point_token|
  7423. after the integer part of such a fraction has been scanned by |scan_int|,
  7424. and that the decimal point has been backed up to be scanned again.
  7425. @p procedure scan_int; {sets |cur_val| to an integer}
  7426. label done;
  7427. var negative:boolean; {should the answer be negated?}
  7428. @!m:integer; {|@t$2^{31}$@> div radix|, the threshold of danger}
  7429. @!d:small_number; {the digit just scanned}
  7430. @!vacuous:boolean; {have no digits appeared?}
  7431. @!OK_so_far:boolean; {has an error message been issued?}
  7432. begin radix:=0; OK_so_far:=true;@/
  7433. @<Get the next non-blank non-sign token; set |negative| appropriately@>;
  7434. if cur_tok=alpha_token then @<Scan an alphabetic character code into |cur_val|@>
  7435. else if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7436.   scan_something_internal(int_val,false)
  7437. else @<Scan a numeric constant@>;
  7438. if negative then negate(cur_val);
  7439. @ @<Get the next non-blank non-sign token...@>=
  7440. negative:=false;
  7441. repeat @<Get the next non-blank non-call token@>;
  7442. if cur_tok=other_token+"-" then
  7443.   begin negative := not negative; cur_tok:=other_token+"+";
  7444.   end;
  7445. until cur_tok<>other_token+"+"
  7446. @ A space is ignored after an alphabetic character constant, so that
  7447. such constants behave like numeric ones.
  7448. @<Scan an alphabetic character code into |cur_val|@>=
  7449. begin get_token; {suppress macro expansion}
  7450. if cur_tok<cs_token_flag then
  7451.   begin cur_val:=cur_chr;
  7452.   if cur_cmd<=right_brace then
  7453.     if cur_cmd=right_brace then incr(align_state)
  7454.     else decr(align_state);
  7455.   end
  7456. else if cur_tok<cs_token_flag+single_base then
  7457.   cur_val:=cur_tok-cs_token_flag-active_base
  7458. else cur_val:=cur_tok-cs_token_flag-single_base;
  7459. if cur_val>255 then
  7460.   begin print_err("Improper alphabetic constant");
  7461. @.Improper alphabetic constant@>
  7462.   help2("A one-character control sequence belongs after a ` mark.")@/
  7463.     ("So I'm essentially inserting \0 here.");
  7464.   cur_val:="0"; back_error;
  7465.   end
  7466. else @<Scan an optional space@>;
  7467. @ @<Scan an optional space@>=
  7468. begin get_x_token; if cur_cmd<>spacer then back_input;
  7469. @ @<Scan a numeric constant@>=
  7470. begin radix:=10; m:=214748364;
  7471. if cur_tok=octal_token then
  7472.   begin radix:=8; m:=@'2000000000; get_x_token;
  7473.   end
  7474. else if cur_tok=hex_token then
  7475.   begin radix:=16; m:=@'1000000000; get_x_token;
  7476.   end;
  7477. vacuous:=true; cur_val:=0;@/
  7478. @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
  7479. if vacuous then @<Express astonishment that no number was here@>
  7480. else if cur_cmd<>spacer then back_input;
  7481. @ @d infinity==@'17777777777 {the largest positive value that \TeX\ knows}
  7482. @d zero_token=other_token+"0" {zero, the smallest digit}
  7483. @d A_token=letter_token+"A" {the smallest special hex digit}
  7484. @d other_A_token=other_token+"A" {special hex digit of type |other_char|}
  7485. @<Accumulate the constant...@>=
  7486. loop@+  begin if (cur_tok<zero_token+radix)and(cur_tok>=zero_token)and
  7487.     (cur_tok<=zero_token+9) then d:=cur_tok-zero_token
  7488.   else if radix=16 then
  7489.     if (cur_tok<=A_token+5)and(cur_tok>=A_token) then d:=cur_tok-A_token+10
  7490.     else if (cur_tok<=other_A_token+5)and(cur_tok>=other_A_token) then
  7491.       d:=cur_tok-other_A_token+10
  7492.     else goto done
  7493.   else goto done;
  7494.   vacuous:=false;
  7495.   if (cur_val>=m)and((cur_val>m)or(d>7)or(radix<>10)) then
  7496.     begin if OK_so_far then
  7497.       begin print_err("Number too big");
  7498. @.Number too big@>
  7499.       help2("I can only go up to 2147483647='17777777777=""7FFFFFFF,")@/
  7500.         ("so I'm using that number instead of yours.");
  7501.       error; cur_val:=infinity; OK_so_far:=false;
  7502.       end;
  7503.     end
  7504.   else cur_val:=cur_val*radix+d;
  7505.   get_x_token;
  7506.   end;
  7507. done:
  7508. @ @<Express astonishment...@>=
  7509. begin print_err("Missing number, treated as zero");
  7510. @.Missing number...@>
  7511. help3("A number should have been here; I inserted `0'.")@/
  7512.   ("(If you can't figure out why I needed to see a number,")@/
  7513.   ("look up `weird error' in the index to The TeXbook.)");
  7514. @:TeXbook}{\sl The \TeX book@>
  7515. back_error;
  7516. @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
  7517. a |scaled| value, i.e., an integral number of sp. One of its main tasks
  7518. is therefore to interpret the abbreviations for various kinds of units and
  7519. to convert measurements to scaled points.
  7520. There are three parameters: |mu| is |true| if the finite units must be
  7521. `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
  7522. |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
  7523. are permitted; and |shortcut| is |true| if |cur_val| already contains
  7524. an integer and only the units need to be considered.
  7525. The order of infinity that was found in the case of infinite glue is returned
  7526. in the global variable |cur_order|.
  7527. @<Glob...@>=
  7528. @!cur_order:glue_ord; {order of infinity found by |scan_dimen|}
  7529. @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
  7530. may begin with |scan_int|. This explains why it is convenient to use
  7531. |scan_int| also for the integer part of a decimal fraction.
  7532. Several branches of |scan_dimen| work with |cur_val| as an integer and
  7533. with an auxiliary fraction |f|, so that the actual quantity of interest is
  7534. $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
  7535. representation is put into the single word |cur_val|, which suddenly
  7536. switches significance from |integer| to |scaled|.
  7537. @d attach_fraction=88 {go here to pack |cur_val| and |f| into |cur_val|}
  7538. @d attach_sign=89 {go here when |cur_val| is correct except perhaps for sign}
  7539. @d scan_normal_dimen==scan_dimen(false,false,false)
  7540. @p procedure scan_dimen(@!mu,@!inf,@!shortcut:boolean);
  7541.   {sets |cur_val| to a dimension}
  7542. label done, done1, done2, found, not_found, attach_fraction, attach_sign;
  7543. var negative:boolean; {should the answer be negated?}
  7544. @!f:integer; {numerator of a fraction whose denominator is $2^{16}$}
  7545. @<Local variables for dimension calculations@>@;
  7546. begin f:=0; arith_error:=false; cur_order:=normal; negative:=false;
  7547. if not shortcut then
  7548.   begin @<Get the next non-blank non-sign...@>;
  7549.   if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7550.     @<Fetch an internal dimension and |goto attach_sign|,
  7551.       or fetch an internal integer@>
  7552.   else  begin back_input;
  7553.     if cur_tok=continental_point_token then cur_tok:=point_token;
  7554.     if cur_tok<>point_token then scan_int
  7555.     else  begin radix:=10; cur_val:=0;
  7556.       end;
  7557.     if cur_tok=continental_point_token then cur_tok:=point_token;
  7558.     if (radix=10)and(cur_tok=point_token) then @<Scan decimal fraction@>;
  7559.     end;
  7560.   end;
  7561. if cur_val<0 then {in this case |f=0|}
  7562.   begin negative := not negative; negate(cur_val);
  7563.   end;
  7564. @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
  7565.   are |x| sp per unit; |goto attach_sign| if the units are internal@>;
  7566. @<Scan an optional space@>;
  7567. attach_sign: if arith_error or(abs(cur_val)>=@'10000000000) then
  7568.   @<Report that this dimension is out of range@>;
  7569. if negative then negate(cur_val);
  7570. @ @<Fetch an internal dimension and |goto attach_sign|...@>=
  7571. if mu then
  7572.   begin scan_something_internal(mu_val,false);
  7573.   @<Coerce glue to a dimension@>;
  7574.   if cur_val_level=mu_val then goto attach_sign;
  7575.   if cur_val_level<>int_val then mu_error;
  7576.   end
  7577. else  begin scan_something_internal(dimen_val,false);
  7578.   if cur_val_level=dimen_val then goto attach_sign;
  7579.   end
  7580. @ @<Local variables for dimension calculations@>=
  7581. @!num,@!denom:1..65536; {conversion ratio for the scanned units}
  7582. @!k,@!kk:small_number; {number of digits in a decimal fraction}
  7583. @!p,@!q:pointer; {top of decimal digit stack}
  7584. @!v:scaled; {an internal dimension}
  7585. @!save_cur_val:integer; {temporary storage of |cur_val|}
  7586. @ The following code is executed when |scan_something_internal| was
  7587. called asking for |mu_val|, when we really wanted a ``mudimen'' instead
  7588. of ``muglue.''
  7589. @<Coerce glue to a dimension@>=
  7590. if cur_val_level>=glue_val then
  7591.   begin v:=width(cur_val); delete_glue_ref(cur_val); cur_val:=v;
  7592.   end
  7593. @ When the following code is executed, we have |cur_tok=point_token|, but this
  7594. token has been backed up using |back_input|; we must first discard it.
  7595. It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
  7596. Let's hope people don't use that fact.
  7597. @<Scan decimal fraction@>=
  7598. begin k:=0; p:=null; get_token; {|point_token| is being re-scanned}
  7599. loop@+  begin get_x_token;
  7600.   if (cur_tok>zero_token+9)or(cur_tok<zero_token) then goto done1;
  7601.   if k<17 then {digits for |k>=17| cannot affect the result}
  7602.     begin q:=get_avail; link(q):=p; info(q):=cur_tok-zero_token;
  7603.     p:=q; incr(k);
  7604.     end;
  7605.   end;
  7606. done1: for kk:=k downto 1 do
  7607.   begin dig[kk-1]:=info(p); q:=p; p:=link(p); free_avail(q);
  7608.   end;
  7609. f:=round_decimals(k);
  7610. if cur_cmd<>spacer then back_input;
  7611. @ Now comes the harder part: At this point in the program, |cur_val| is a
  7612. nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
  7613. we want to multiply the sum of these two quantities by the appropriate
  7614. factor, based on the specified units, in order to produce a |scaled|
  7615. result, and we want to do the calculation with fixed point arithmetic that
  7616. does not overflow.
  7617. @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
  7618. if inf then @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
  7619. @<Scan for \(u)units that are internal dimensions;
  7620.   |goto attach_sign| with |cur_val| set if found@>;
  7621. if mu then @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
  7622. if scan_keyword("true") then @<Adjust \(f)for the magnification ratio@>;
  7623. @.true@>
  7624. if scan_keyword("pt") then goto attach_fraction; {the easy case}
  7625. @.pt@>
  7626. @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly;
  7627.   |goto done| in the case of scaled points@>;
  7628. attach_fraction: if cur_val>=@'40000 then arith_error:=true
  7629. else cur_val:=cur_val*unity+f;
  7630. done:
  7631. @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
  7632. error messages (one for each additional keyword \.{"l"}).
  7633. @<Scan for \(f)\.{fil} units...@>=
  7634. if scan_keyword("fil") then
  7635. @.fil@>
  7636.   begin cur_order:=fil;
  7637.   while scan_keyword("l") do
  7638.     begin if cur_order=filll then
  7639.       begin print_err("Illegal unit of measure (");
  7640. @.Illegal unit of measure@>
  7641.       print("replaced by filll)");
  7642.       help1("I dddon't go any higher than filll."); error;
  7643.       end
  7644.     else incr(cur_order);
  7645.     end;
  7646.   goto attach_fraction;
  7647.   end
  7648. @ @<Scan for \(u)units that are internal dimensions...@>=
  7649. save_cur_val:=cur_val;
  7650. @<Get the next non-blank non-call...@>;
  7651. if (cur_cmd<min_internal)or(cur_cmd>max_internal) then back_input
  7652. else  begin if mu then
  7653.     begin scan_something_internal(mu_val,false); @<Coerce glue...@>;
  7654.     if cur_val_level<>mu_val then mu_error;
  7655.     end
  7656.   else scan_something_internal(dimen_val,false);
  7657.   v:=cur_val; goto found;
  7658.   end;
  7659. if mu then goto not_found;
  7660. if scan_keyword("em") then v:=(@<The em width for |cur_font|@>)
  7661. @.em@>
  7662. else if scan_keyword("ex") then v:=(@<The x-height for |cur_font|@>)
  7663. @.ex@>
  7664. else goto not_found;
  7665. @<Scan an optional space@>;
  7666. found:cur_val:=nx_plus_y(save_cur_val,v,xn_over_d(v,f,@'200000));
  7667. goto attach_sign;
  7668. not_found:
  7669. @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
  7670. if scan_keyword("mu") then goto attach_fraction
  7671. @.mu@>
  7672. else  begin print_err("Illegal unit of measure ("); print("mu inserted)");
  7673. @.Illegal unit of measure@>
  7674.   help4("The unit of measurement in math glue must be mu.")@/
  7675.     ("To recover gracefully from this error, it's best to")@/
  7676.     ("delete the erroneous units; e.g., type `2' to delete")@/
  7677.     ("two letters. (See Chapter 27 of The TeXbook.)");
  7678. @:TeXbook}{\sl The \TeX book@>
  7679.   error; goto attach_fraction;
  7680.   end
  7681. @ @<Adjust \(f)for the magnification ratio@>=
  7682. begin prepare_mag;
  7683. if mag<>1000 then
  7684.   begin cur_val:=xn_over_d(cur_val,1000,mag);
  7685.   f:=(1000*f+@'200000*remainder) div mag;
  7686.   cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
  7687.   end;
  7688. @ The necessary conversion factors can all be specified exactly as
  7689. fractions whose numerator and denominator are 32768 or less.
  7690. According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
  7691. this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
  7692. @^Bosshard, Hans Rudolf@>
  7693. in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
  7694. @d set_conversion_end(#)== denom:=#; end
  7695. @d set_conversion(#)==@+begin num:=#; set_conversion_end
  7696. @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
  7697. if scan_keyword("in") then set_conversion(7227)(100)
  7698. @.in@>
  7699. else if scan_keyword("pc") then set_conversion(12)(1)
  7700. @.pc@>
  7701. else if scan_keyword("cm") then set_conversion(7227)(254)
  7702. @.cm@>
  7703. else if scan_keyword("mm") then set_conversion(7227)(2540)
  7704. @.mm@>
  7705. else if scan_keyword("bp") then set_conversion(7227)(7200)
  7706. @.bp@>
  7707. else if scan_keyword("dd") then set_conversion(1238)(1157)
  7708. @.dd@>
  7709. else if scan_keyword("cc") then set_conversion(14856)(1157)
  7710. @.cc@>
  7711. else if scan_keyword("sp") then goto done
  7712. @.sp@>
  7713. else @<Complain about unknown unit and |goto done2|@>;
  7714. cur_val:=xn_over_d(cur_val,num,denom);
  7715. f:=(num*f+@'200000*remainder) div denom;@/
  7716. cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
  7717. done2:
  7718. @ @<Complain about unknown unit...@>=
  7719. begin print_err("Illegal unit of measure ("); print("pt inserted)");
  7720. @.Illegal unit of measure@>
  7721. help6("Dimensions can be in units of em, ex, in, pt, pc,")@/
  7722.   ("cm, mm, dd, cc, bp, or sp; but yours is a new one!")@/
  7723.   ("I'll assume that you meant to say pt, for printer's points.")@/
  7724.   ("To recover gracefully from this error, it's best to")@/
  7725.   ("delete the erroneous units; e.g., type `2' to delete")@/
  7726.   ("two letters. (See Chapter 27 of The TeXbook.)");
  7727. @:TeXbook}{\sl The \TeX book@>
  7728. error; goto done2;
  7729. @ @<Report that this dimension is out of range@>=
  7730. begin print_err("Dimension too large");
  7731. @.Dimension too large@>
  7732. help2("I can't work with sizes bigger than about 19 feet.")@/
  7733.   ("Continue and I'll use the largest value I can.");@/
  7734. error; cur_val:=max_dimen; arith_error:=false;
  7735. @ The final member of \TeX's value-scanning trio is |scan_glue|, which
  7736. makes |cur_val| point to a glue specification. The reference count of that
  7737. glue spec will take account of the fact that |cur_val| is pointing to~it.
  7738. The |level| parameter should be either |glue_val| or |mu_val|.
  7739. Since |scan_dimen| was so much more complex than |scan_int|, we might expect
  7740. |scan_glue| to be even worse. But fortunately, it is very simple, since
  7741. most of the work has already been done.
  7742. @p procedure scan_glue(@!level:small_number);
  7743.   {sets |cur_val| to a glue spec pointer}
  7744. label exit;
  7745. var negative:boolean; {should the answer be negated?}
  7746. @!q:pointer; {new glue specification}
  7747. @!mu:boolean; {does |level=mu_val|?}
  7748. begin mu:=(level=mu_val); @<Get the next non-blank non-sign...@>;
  7749. if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7750.   begin scan_something_internal(level,negative);
  7751.   if cur_val_level>=glue_val then
  7752.     begin if cur_val_level<>level then mu_error;
  7753.     return;
  7754.     end;
  7755.   if cur_val_level=int_val then scan_dimen(mu,false,true)
  7756.   else if level=mu_val then mu_error;
  7757.   end
  7758. else  begin back_input; scan_dimen(mu,false,false);
  7759.   if negative then negate(cur_val);
  7760.   end;
  7761. @<Create a new glue specification whose width is |cur_val|; scan for its
  7762.   stretch and shrink components@>;
  7763. exit:end;
  7764. @ @<Create a new glue specification whose width is |cur_val|...@>=
  7765. q:=new_spec(zero_glue); width(q):=cur_val;
  7766. if scan_keyword("plus") then
  7767. @.plus@>
  7768.   begin scan_dimen(mu,true,false);
  7769.   stretch(q):=cur_val; stretch_order(q):=cur_order;
  7770.   end;
  7771. if scan_keyword("minus") then
  7772. @.minus@>
  7773.   begin scan_dimen(mu,true,false);
  7774.   shrink(q):=cur_val; shrink_order(q):=cur_order;
  7775.   end;
  7776. cur_val:=q
  7777. @ Here's a similar procedure that returns a pointer to a rule node. This
  7778. routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
  7779. therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
  7780. the default rule dimensions in the node, then to override them if
  7781. `\.{height}' or `\.{width}' or `\.{depth}' specifications are
  7782. found (in any order).
  7783. @d default_rule=26214 {0.4\thinspace pt}
  7784. @p function scan_rule_spec:pointer;
  7785. label reswitch;
  7786. var q:pointer; {the rule node being created}
  7787. begin q:=new_rule; {|width|, |depth|, and |height| all equal |null_flag| now}
  7788. if cur_cmd=vrule then width(q):=default_rule
  7789. else  begin height(q):=default_rule; depth(q):=0;
  7790.   end;
  7791. reswitch: if scan_keyword("width") then
  7792. @.width@>
  7793.   begin scan_normal_dimen; width(q):=cur_val; goto reswitch;
  7794.   end;
  7795. if scan_keyword("height") then
  7796. @.height@>
  7797.   begin scan_normal_dimen; height(q):=cur_val; goto reswitch;
  7798.   end;
  7799. if scan_keyword("depth") then
  7800. @.depth@>
  7801.   begin scan_normal_dimen; depth(q):=cur_val; goto reswitch;
  7802.   end;
  7803. scan_rule_spec:=q;
  7804. @* \[27] Building token lists.
  7805. The token lists for macros and for other things like \.{\\mark} and \.{\\output}
  7806. and \.{\\write} are produced by a procedure called |scan_toks|.
  7807. Before we get into the details of |scan_toks|, let's consider a much
  7808. simpler task, that of converting the current string into a token list.
  7809. The |str_toks| function does this; it classifies spaces as type |spacer|
  7810. and everything else as type |other_char|.
  7811. The token list created by |str_toks| begins at |link(temp_head)| and ends
  7812. at the value |p| that is returned. (If |p=temp_head|, the list is empty.)
  7813. @p function str_toks(@!b:pool_pointer):pointer;
  7814.   {changes the string |str_pool[b..pool_ptr]| to a token list}
  7815. var p:pointer; {tail of the token list}
  7816. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7817. @!t:halfword; {token being appended}
  7818. @!k:pool_pointer; {index into |str_pool|}
  7819. begin str_room(1);
  7820. p:=temp_head; link(p):=null; k:=b;
  7821. while k<pool_ptr do
  7822.   begin t:=so(str_pool[k]);
  7823.   if t=" " then t:=space_token
  7824.   else t:=other_token+t;
  7825.   fast_store_new_token(t);
  7826.   incr(k);
  7827.   end;
  7828. pool_ptr:=b; str_toks:=p;
  7829. @ The main reason for wanting |str_toks| is the next function,
  7830. |the_toks|, which has similar input/output characteristics.
  7831. This procedure is supposed to scan something like `\.{\\skip\\count12}',
  7832. i.e., whatever can follow `\.{\\the}', and it constructs a token list
  7833. containing something like `\.{-3.0pt minus 0.5fill}'.
  7834. @p function the_toks:pointer;
  7835. var old_setting:0..max_selector; {holds |selector| setting}
  7836. @!p,@!q,@!r:pointer; {used for copying a token list}
  7837. @!b:pool_pointer; {base of temporary string}
  7838. begin get_x_token; scan_something_internal(tok_val,false);
  7839. if cur_val_level>=ident_val then @<Copy the token list@>
  7840. else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
  7841.   case cur_val_level of
  7842.   int_val:print_int(cur_val);
  7843.   dimen_val:begin print_scaled(cur_val); print("pt");
  7844.     end;
  7845.   glue_val: begin print_spec(cur_val,"pt"); delete_glue_ref(cur_val);
  7846.     end;
  7847.   mu_val: begin print_spec(cur_val,"mu"); delete_glue_ref(cur_val);
  7848.     end;
  7849.   end; {there are no other cases}
  7850.   selector:=old_setting; the_toks:=str_toks(b);
  7851.   end;
  7852. @ @<Copy the token list@>=
  7853. begin p:=temp_head; link(p):=null;
  7854. if cur_val_level=ident_val then store_new_token(cs_token_flag+cur_val)
  7855. else if cur_val<>null then
  7856.   begin r:=link(cur_val); {do not copy the reference count}
  7857.   while r<>null do
  7858.     begin fast_store_new_token(info(r)); r:=link(r);
  7859.     end;
  7860.   end;
  7861. the_toks:=p;
  7862. @ Here's part of the |expand| subroutine that we are now ready to complete:
  7863. @p procedure ins_the_toks;
  7864. begin link(garbage):=the_toks; ins_list(link(temp_head));
  7865. @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
  7866. \.{\\fontname}, and \.{\\jobname} are defined as follows.
  7867. @d number_code=0 {command code for \.{\\number}}
  7868. @d roman_numeral_code=1 {command code for \.{\\romannumeral}}
  7869. @d string_code=2 {command code for \.{\\string}}
  7870. @d meaning_code=3 {command code for \.{\\meaning}}
  7871. @d font_name_code=4 {command code for \.{\\fontname}}
  7872. @d job_name_code=5 {command code for \.{\\jobname}}
  7873. @<Put each...@>=
  7874. primitive("number",convert,number_code);@/
  7875. @!@:number_}{\.{\\number} primitive@>
  7876. primitive("romannumeral",convert,roman_numeral_code);@/
  7877. @!@:roman_numeral_}{\.{\\romannumeral} primitive@>
  7878. primitive("string",convert,string_code);@/
  7879. @!@:string_}{\.{\\string} primitive@>
  7880. primitive("meaning",convert,meaning_code);@/
  7881. @!@:meaning_}{\.{\\meaning} primitive@>
  7882. primitive("fontname",convert,font_name_code);@/
  7883. @!@:font_name_}{\.{\\fontname} primitive@>
  7884. primitive("jobname",convert,job_name_code);@/
  7885. @!@:job_name_}{\.{\\jobname} primitive@>
  7886. @ @<Cases of |print_cmd_chr|...@>=
  7887. convert: case chr_code of
  7888.   number_code: print_esc("number");
  7889.   roman_numeral_code: print_esc("romannumeral");
  7890.   string_code: print_esc("string");
  7891.   meaning_code: print_esc("meaning");
  7892.   font_name_code: print_esc("fontname");
  7893.   othercases print_esc("jobname")
  7894.   endcases;
  7895. @ The procedure |conv_toks| uses |str_toks| to insert the token list
  7896. for |convert| functions into the scanner; `\.{\\outer}' control sequences
  7897. are allowed to follow `\.{\\string}' and `\.{\\meaning}'.
  7898. @p procedure conv_toks;
  7899. var old_setting:0..max_selector; {holds |selector| setting}
  7900. @!c:number_code..job_name_code; {desired type of conversion}
  7901. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  7902. @!b:pool_pointer; {base of temporary string}
  7903. begin c:=cur_chr; @<Scan the argument for command |c|@>;
  7904. old_setting:=selector; selector:=new_string; b:=pool_ptr;
  7905. @<Print the result of command |c|@>;
  7906. selector:=old_setting; link(garbage):=str_toks(b); ins_list(link(temp_head));
  7907. @ @<Scan the argument for command |c|@>=
  7908. case c of
  7909. number_code,roman_numeral_code: scan_int;
  7910. string_code, meaning_code: begin save_scanner_status:=scanner_status;
  7911.   scanner_status:=normal; get_token; scanner_status:=save_scanner_status;
  7912.   end;
  7913. font_name_code: scan_font_ident;
  7914. job_name_code: if job_name=0 then open_log_file;
  7915. end {there are no other cases}
  7916. @ @<Print the result of command |c|@>=
  7917. case c of
  7918. number_code: print_int(cur_val);
  7919. roman_numeral_code: print_roman_int(cur_val);
  7920. string_code:if cur_cs<>0 then sprint_cs(cur_cs)
  7921.   else print_char(cur_chr);
  7922. meaning_code: print_meaning;
  7923. font_name_code: begin print(font_name[cur_val]);
  7924.   if font_size[cur_val]<>font_dsize[cur_val] then
  7925.     begin print(" at "); print_scaled(font_size[cur_val]);
  7926.     print("pt");
  7927.     end;
  7928.   end;
  7929. job_name_code: print(job_name);
  7930. end {there are no other cases}
  7931. @ Now we can't postpone the difficulties any longer; we must bravely tackle
  7932. |scan_toks|. This function returns a pointer to the tail of a new token
  7933. list, and it also makes |def_ref| point to the reference count at the
  7934. head of that list.
  7935. There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
  7936. is true, the goal is to create the token list for a macro definition;
  7937. otherwise the goal is to create the token list for some other \TeX\
  7938. primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
  7939. \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
  7940. \.{\\special}. In the latter cases a left brace must be scanned next; this
  7941. left brace will not be part of the token list, nor will the matching right
  7942. brace that comes at the end. If |xpand| is false, the token list will
  7943. simply be copied from the input using |get_token|. Otherwise all expandable
  7944. tokens will be expanded until unexpandable tokens are left, except that
  7945. the results of expanding `\.{\\the}' are not expanded further.
  7946. If both |macro_def| and |xpand| are true, the expansion applies
  7947. only to the macro body (i.e., to the material following the first
  7948. |left_brace| character).
  7949. The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
  7950. address of the control sequence to display in ``runaway'' error
  7951. messages.
  7952. @p function scan_toks(@!macro_def,@!xpand:boolean):pointer;
  7953. label found,done,done1,done2;
  7954. var t:halfword; {token representing the highest parameter number}
  7955. @!s:halfword; {saved token}
  7956. @!p:pointer; {tail of the token list being built}
  7957. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7958. @!unbalance:halfword; {number of unmatched left braces}
  7959. @!hash_brace:halfword; {possible `\.{\#\{}' token}
  7960. begin if macro_def then scanner_status:=defining
  7961. @+else scanner_status:=absorbing;
  7962. warning_index:=cur_cs; def_ref:=get_avail; token_ref_count(def_ref):=null;
  7963. p:=def_ref; hash_brace:=0; t:=zero_token;
  7964. if macro_def then @<Scan and build the parameter part of the macro definition@>
  7965. else scan_left_brace; {remove the compulsory left brace}
  7966. @<Scan and build the body of the token list; |goto found| when finished@>;
  7967. found: scanner_status:=normal;
  7968. if hash_brace<>0 then store_new_token(hash_brace);
  7969. scan_toks:=p;
  7970. @ @<Scan and build the parameter part...@>=
  7971. begin loop begin get_token; {set |cur_cmd|, |cur_chr|, |cur_tok|}
  7972.   if cur_tok<right_brace_limit then goto done1;
  7973.   if cur_cmd=mac_param then
  7974.     @<If the next character is a parameter number, make |cur_tok|
  7975.       a |match| token; but if it is a left brace, store
  7976.       `|left_brace|, |end_match|', set |hash_brace|, and |goto done|@>;
  7977.   store_new_token(cur_tok);
  7978.   end;
  7979. done1: store_new_token(end_match_token);
  7980. if cur_cmd=right_brace then
  7981.   @<Express shock at the missing left brace; |goto found|@>;
  7982. done: end
  7983. @ @<Express shock...@>=
  7984. begin print_err("Missing { inserted"); incr(align_state);
  7985. @.Missing \{ inserted@>
  7986. help2("Where was the left brace? You said something like `\def\a}',")@/
  7987.   ("which I'm going to interpret as `\def\a{}'."); error; goto found;
  7988. @ @<If the next character is a parameter number...@>=
  7989. begin s:=match_token+cur_chr; get_token;
  7990. if cur_cmd=left_brace then
  7991.   begin hash_brace:=cur_tok;
  7992.   store_new_token(cur_tok); store_new_token(end_match_token);
  7993.   goto done;
  7994.   end;
  7995. if t=zero_token+9 then
  7996.   begin print_err("You already have nine parameters");
  7997. @.You already have nine...@>
  7998.   help1("I'm going to ignore the # sign you just used."); error;
  7999.   end
  8000. else  begin incr(t);
  8001.   if cur_tok<>t then
  8002.     begin print_err("Parameters must be numbered consecutively");
  8003. @.Parameters...consecutively@>
  8004.     help2("I've inserted the digit you should have used after the #.")@/
  8005.       ("Type `1' to delete what you did use."); back_error;
  8006.     end;
  8007.   cur_tok:=s;
  8008.   end;
  8009. @ @<Scan and build the body of the token list; |goto found| when finished@>=
  8010. unbalance:=1;
  8011. loop@+  begin if xpand then @<Expand the next part of the input@>
  8012.   else get_token;
  8013.   if cur_tok<right_brace_limit then
  8014.     if cur_cmd<right_brace then incr(unbalance)
  8015.     else  begin decr(unbalance);
  8016.       if unbalance=0 then goto found;
  8017.       end
  8018.   else if cur_cmd=mac_param then
  8019.     if macro_def then @<Look for parameter number or \.{\#\#}@>;
  8020.   store_new_token(cur_tok);
  8021.   end
  8022. @ Here we insert an entire token list created by |the_toks| without
  8023. expanding it further.
  8024. @<Expand the next part of the input@>=
  8025. begin loop begin get_next;
  8026.   if cur_cmd<=max_command then goto done2;
  8027.   if cur_cmd<>the then expand
  8028.   else  begin q:=the_toks;
  8029.     if link(temp_head)<>null then
  8030.       begin link(p):=link(temp_head); p:=q;
  8031.       end;
  8032.     end;
  8033.   end;
  8034. done2: x_token
  8035. @ @<Look for parameter number...@>=
  8036. begin s:=cur_tok;
  8037. if xpand then get_x_token else get_token;
  8038. if cur_cmd<>mac_param then
  8039.   if (cur_tok<=zero_token)or(cur_tok>t) then
  8040.     begin print_err("Illegal parameter number in definition of ");
  8041. @.Illegal parameter number...@>
  8042.     sprint_cs(warning_index);
  8043.     help3("You meant to type ## instead of #, right?")@/
  8044.     ("Or maybe a } was forgotten somewhere earlier, and things")@/
  8045.     ("are all screwed up? I'm going to assume that you meant ##.");
  8046.     back_error; cur_tok:=s;
  8047.     end
  8048.   else cur_tok:=out_param_token-"0"+cur_chr;
  8049. @ Another way to create a token list is via the \.{\\read} command. The
  8050. sixteen files potentially usable for reading appear in the following
  8051. global variables. The value of |read_open[n]| will be |closed| if
  8052. stream number |n| has not been opened or if it has been fully read;
  8053. |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
  8054. and |normal| if it is open and ready to read the next line.
  8055. @d closed=2 {not open, or at end of file}
  8056. @d just_open=1 {newly opened, first line not yet read}
  8057. @<Glob...@>=
  8058. @!read_file:array[0..15] of alpha_file; {used for \.{\\read}}
  8059. @!read_open:array[0..16] of normal..closed; {state of |read_file[n]|}
  8060. @ @<Set init...@>=
  8061. for k:=0 to 16 do read_open[k]:=closed;
  8062. @ The |read_toks| procedure constructs a token list like that for any
  8063. macro definition, and makes |cur_val| point to it. Parameter |r| points
  8064. to the control sequence that will receive this token list.
  8065. @p procedure read_toks(@!n:integer;@!r:pointer);
  8066. label done;
  8067. var p:pointer; {tail of the token list}
  8068. @!q:pointer; {new node being added to the token list via |store_new_token|}
  8069. @!s:integer; {saved value of |align_state|}
  8070. @!m:small_number; {stream number}
  8071. begin scanner_status:=defining; warning_index:=r;
  8072. def_ref:=get_avail; token_ref_count(def_ref):=null;
  8073. p:=def_ref; {the reference count}
  8074. store_new_token(end_match_token);
  8075. if (n<0)or(n>15) then m:=16@+else m:=n;
  8076. s:=align_state; align_state:=1000000; {disable tab marks, etc.}
  8077. repeat @<Input and store tokens from the next line of the file@>;
  8078. until align_state=1000000;
  8079. cur_val:=def_ref; scanner_status:=normal; align_state:=s;
  8080. @ @<Input and store tokens from the next line of the file@>=
  8081. begin_file_reading; name:=m+1;
  8082. if read_open[m]=closed then @<Input for \.{\\read} from the terminal@>
  8083. else if read_open[m]=just_open then @<Input the first line of |read_file[m]|@>
  8084. else @<Input the next line of |read_file[m]|@>;
  8085. limit:=last;
  8086. if end_line_char_inactive then decr(limit)
  8087. else  buffer[limit]:=end_line_char;
  8088. first:=limit+1; loc:=start; state:=new_line;@/
  8089. loop@+  begin get_token;
  8090.   if cur_tok=0 then goto done;
  8091.     {|cur_cmd=cur_chr=0| will occur at the end of the line}
  8092.   if align_state<1000000 then {unmatched `\.\}' aborts the line}
  8093.     begin repeat get_token; until cur_tok=0;
  8094.     align_state:=1000000; goto done;
  8095.     end;
  8096.   store_new_token(cur_tok);
  8097.   end;
  8098. done: end_file_reading
  8099. @ Here we input on-line into the |buffer| array, prompting the user explicitly
  8100. if |n>=0|.  The value of |n| is set negative so that additional prompts
  8101. will not be given in the case of multi-line input.
  8102. @<Input for \.{\\read} from the terminal@>=
  8103. if interaction>nonstop_mode then
  8104.   if n<0 then prompt_input("")
  8105.   else  begin wake_up_terminal;
  8106.     print_ln; sprint_cs(r); prompt_input("="); n:=-1;
  8107.     end
  8108. else fatal_error("*** (cannot \read from terminal in nonstop modes)")
  8109. @.cannot \\read@>
  8110. @ The first line of a file must be treated specially, since |input_ln|
  8111. must be told not to start with |get|.
  8112. @^system dependencies@>
  8113. @<Input the first line of |read_file[m]|@>=
  8114. if input_ln(read_file[m],false) then read_open[m]:=normal
  8115. else  begin a_close(read_file[m]); read_open[m]:=closed;
  8116.   end
  8117. @ An empty line is appended at the end of a |read_file|.
  8118. @^empty line at end of file@>
  8119. @<Input the next line of |read_file[m]|@>=
  8120. begin if not input_ln(read_file[m],true) then
  8121.   begin a_close(read_file[m]); read_open[m]:=closed;
  8122.   if align_state<>1000000 then
  8123.     begin runaway;
  8124.     print_err("File ended within "); print_esc("read");
  8125. @.File ended within \\read@>
  8126.     help1("This \read has unbalanced braces.");
  8127.     align_state:=1000000; error;
  8128.     end;
  8129.   end;
  8130. @* \[28] Conditional processing.
  8131. We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
  8132. @d if_char_code=0 { `\.{\\if}' }
  8133. @d if_cat_code=1 { `\.{\\ifcat}' }
  8134. @d if_int_code=2 { `\.{\\ifnum}' }
  8135. @d if_dim_code=3 { `\.{\\ifdim}' }
  8136. @d if_odd_code=4 { `\.{\\ifodd}' }
  8137. @d if_vmode_code=5 { `\.{\\ifvmode}' }
  8138. @d if_hmode_code=6 { `\.{\\ifhmode}' }
  8139. @d if_mmode_code=7 { `\.{\\ifmmode}' }
  8140. @d if_inner_code=8 { `\.{\\ifinner}' }
  8141. @d if_void_code=9 { `\.{\\ifvoid}' }
  8142. @d if_hbox_code=10 { `\.{\\ifhbox}' }
  8143. @d if_vbox_code=11 { `\.{\\ifvbox}' }
  8144. @d ifx_code=12 { `\.{\\ifx}' }
  8145. @d if_eof_code=13 { `\.{\\ifeof}' }
  8146. @d if_true_code=14 { `\.{\\iftrue}' }
  8147. @d if_false_code=15 { `\.{\\iffalse}' }
  8148. @d if_case_code=16 { `\.{\\ifcase}' }
  8149. @<Put each...@>=
  8150. primitive("if",if_test,if_char_code);
  8151. @!@:if_char_}{\.{\\if} primitive@>
  8152. primitive("ifcat",if_test,if_cat_code);
  8153. @!@:if_cat_code_}{\.{\\ifcat} primitive@>
  8154. primitive("ifnum",if_test,if_int_code);
  8155. @!@:if_int_}{\.{\\ifnum} primitive@>
  8156. primitive("ifdim",if_test,if_dim_code);
  8157. @!@:if_dim_}{\.{\\ifdim} primitive@>
  8158. primitive("ifodd",if_test,if_odd_code);
  8159. @!@:if_odd_}{\.{\\ifodd} primitive@>
  8160. primitive("ifvmode",if_test,if_vmode_code);
  8161. @!@:if_vmode_}{\.{\\ifvmode} primitive@>
  8162. primitive("ifhmode",if_test,if_hmode_code);
  8163. @!@:if_hmode_}{\.{\\ifhmode} primitive@>
  8164. primitive("ifmmode",if_test,if_mmode_code);
  8165. @!@:if_mmode_}{\.{\\ifmmode} primitive@>
  8166. primitive("ifinner",if_test,if_inner_code);
  8167. @!@:if_inner_}{\.{\\ifinner} primitive@>
  8168. primitive("ifvoid",if_test,if_void_code);
  8169. @!@:if_void_}{\.{\\ifvoid} primitive@>
  8170. primitive("ifhbox",if_test,if_hbox_code);
  8171. @!@:if_hbox_}{\.{\\ifhbox} primitive@>
  8172. primitive("ifvbox",if_test,if_vbox_code);
  8173. @!@:if_vbox_}{\.{\\ifvbox} primitive@>
  8174. primitive("ifx",if_test,ifx_code);
  8175. @!@:ifx_}{\.{\\ifx} primitive@>
  8176. primitive("ifeof",if_test,if_eof_code);
  8177. @!@:if_eof_}{\.{\\ifeof} primitive@>
  8178. primitive("iftrue",if_test,if_true_code);
  8179. @!@:if_true_}{\.{\\iftrue} primitive@>
  8180. primitive("iffalse",if_test,if_false_code);
  8181. @!@:if_false_}{\.{\\iffalse} primitive@>
  8182. primitive("ifcase",if_test,if_case_code);
  8183. @!@:if_case_}{\.{\\ifcase} primitive@>
  8184. @ @<Cases of |print_cmd_chr|...@>=
  8185. if_test: case chr_code of
  8186.   if_cat_code:print_esc("ifcat");
  8187.   if_int_code:print_esc("ifnum");
  8188.   if_dim_code:print_esc("ifdim");
  8189.   if_odd_code:print_esc("ifodd");
  8190.   if_vmode_code:print_esc("ifvmode");
  8191.   if_hmode_code:print_esc("ifhmode");
  8192.   if_mmode_code:print_esc("ifmmode");
  8193.   if_inner_code:print_esc("ifinner");
  8194.   if_void_code:print_esc("ifvoid");
  8195.   if_hbox_code:print_esc("ifhbox");
  8196.   if_vbox_code:print_esc("ifvbox");
  8197.   ifx_code:print_esc("ifx");
  8198.   if_eof_code:print_esc("ifeof");
  8199.   if_true_code:print_esc("iftrue");
  8200.   if_false_code:print_esc("iffalse");
  8201.   if_case_code:print_esc("ifcase");
  8202.   othercases print_esc("if")
  8203.   endcases;
  8204. @ Conditions can be inside conditions, and this nesting has a stack
  8205. that is independent of the |save_stack|.
  8206. Four global variables represent the top of the condition stack:
  8207. |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
  8208. the largest code of a |fi_or_else| command that is syntactically legal;
  8209. |cur_if| is the name of the current type of conditional; and |if_line|
  8210. is the line number at which it began.
  8211. If no conditions are currently in progress, the condition stack has the
  8212. special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
  8213. Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
  8214. |link| fields of the first word contain |if_limit|, |cur_if|, and
  8215. |cond_ptr| at the next level, and the second word contains the
  8216. corresponding |if_line|.
  8217. @d if_node_size=2 {number of words in stack entry for conditionals}
  8218. @d if_line_field(#)==mem[#+1].int
  8219. @d if_code=1 {code for \.{\\if...} being evaluated}
  8220. @d fi_code=2 {code for \.{\\fi}}
  8221. @d else_code=3 {code for \.{\\else}}
  8222. @d or_code=4 {code for \.{\\or}}
  8223. @<Glob...@>=
  8224. @!cond_ptr:pointer; {top of the condition stack}
  8225. @!if_limit:normal..or_code; {upper bound on |fi_or_else| codes}
  8226. @!cur_if:small_number; {type of conditional being worked on}
  8227. @!if_line:integer; {line where that conditional began}
  8228. @ @<Set init...@>=
  8229. cond_ptr:=null; if_limit:=normal; cur_if:=0; if_line:=0;
  8230. @ @<Put each...@>=
  8231. primitive("fi",fi_or_else,fi_code);
  8232. @!@:fi_}{\.{\\fi} primitive@>
  8233. text(frozen_fi):="fi"; eqtb[frozen_fi]:=eqtb[cur_val];
  8234. primitive("or",fi_or_else,or_code);
  8235. @!@:or_}{\.{\\or} primitive@>
  8236. primitive("else",fi_or_else,else_code);
  8237. @!@:else_}{\.{\\else} primitive@>
  8238. @ @<Cases of |print_cmd_chr|...@>=
  8239. fi_or_else: if chr_code=fi_code then print_esc("fi")
  8240.   else if chr_code=or_code then print_esc("or")
  8241.   else print_esc("else");
  8242. @ When we skip conditional text, we keep track of the line number
  8243. where skipping began, for use in error messages.
  8244. @<Glob...@>=
  8245. @!skip_line:integer; {skipping began here}
  8246. @ Here is a procedure that ignores text until coming to an \.{\\or},
  8247. \.{\\else}, or \.{\\fi} at level zero of $\.{\\if}\ldots\.{\\fi}$
  8248. nesting. After it has acted, |cur_chr| will indicate the token that
  8249. was found, but |cur_tok| will not be set (because this makes the
  8250. procedure run faster).
  8251. @p procedure pass_text;
  8252. label done;
  8253. var l:integer; {level of $\.{\\if}\ldots\.{\\fi}$ nesting}
  8254. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  8255. begin save_scanner_status:=scanner_status; scanner_status:=skipping; l:=0;
  8256. skip_line:=line;
  8257. loop@+  begin get_next;
  8258.   if cur_cmd=fi_or_else then
  8259.     begin if l=0 then goto done;
  8260.     if cur_chr=fi_code then decr(l);
  8261.     end
  8262.   else if cur_cmd=if_test then incr(l);
  8263.   end;
  8264. done: scanner_status:=save_scanner_status;
  8265. @ When we begin to process a new \.{\\if}, we set |if_limit:=if_code|; then
  8266. if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
  8267. condition has been evaluated, \.{\\relax} will be inserted.
  8268. For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
  8269. would otherwise require something after the `\.1'.
  8270. @<Push the condition stack@>=
  8271. begin p:=get_node(if_node_size); link(p):=cond_ptr; type(p):=if_limit;
  8272. subtype(p):=cur_if; if_line_field(p):=if_line;
  8273. cond_ptr:=p; cur_if:=cur_chr; if_limit:=if_code; if_line:=line;
  8274. @ @<Pop the condition stack@>=
  8275. begin p:=cond_ptr; if_line:=if_line_field(p);
  8276. cur_if:=subtype(p); if_limit:=type(p); cond_ptr:=link(p);
  8277. free_node(p,if_node_size);
  8278. @ Here's a procedure that changes the |if_limit| code corresponding to
  8279. a given value of |cond_ptr|.
  8280. @p procedure change_if_limit(@!l:small_number;@!p:pointer);
  8281. label exit;
  8282. var q:pointer;
  8283. begin if p=cond_ptr then if_limit:=l {that's the easy case}
  8284. else  begin q:=cond_ptr;
  8285.   loop@+  begin if q=null then confusion("if");
  8286. @:this can't happen if}{\quad if@>
  8287.     if link(q)=p then
  8288.       begin type(q):=l; return;
  8289.       end;
  8290.     q:=link(q);
  8291.     end;
  8292.   end;
  8293. exit:end;
  8294. @ A condition is started when the |expand| procedure encounters
  8295. an |if_test| command; in that case |expand| reduces to |conditional|,
  8296. which is a recursive procedure.
  8297. @^recursion@>
  8298. @p procedure conditional;
  8299. label exit,common_ending;
  8300. var b:boolean; {is the condition true?}
  8301. @!r:"<"..">"; {relation to be evaluated}
  8302. @!m,@!n:integer; {to be tested against the second operand}
  8303. @!p,@!q:pointer; {for traversing token lists in \.{\\ifx} tests}
  8304. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  8305. @!save_cond_ptr:pointer; {|cond_ptr| corresponding to this conditional}
  8306. @!this_if:small_number; {type of this conditional}
  8307. begin @<Push the condition stack@>;@+save_cond_ptr:=cond_ptr;this_if:=cur_chr;@/
  8308. @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
  8309. if tracing_commands>1 then @<Display the value of |b|@>;
  8310. if b then
  8311.   begin change_if_limit(else_code,save_cond_ptr);
  8312.   return; {wait for \.{\\else} or \.{\\fi}}
  8313.   end;
  8314. @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
  8315. common_ending: if cur_chr=fi_code then @<Pop the condition stack@>
  8316. else if_limit:=fi_code; {wait for \.{\\fi}}
  8317. exit:end;
  8318. @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
  8319. \.{\\else} that we come to after learning that the \.{\\if} is false is
  8320. not the \.{\\else} we're looking for. Hence the following curious
  8321. logic is needed.
  8322. @ @<Skip to \.{\\else} or \.{\\fi}...@>=
  8323. loop@+  begin pass_text;
  8324.   if cond_ptr=save_cond_ptr then
  8325.     begin if cur_chr<>or_code then goto common_ending;
  8326.     print_err("Extra "); print_esc("or");
  8327. @.Extra \\or@>
  8328.     help1("I'm ignoring this; it doesn't match any \if.");
  8329.     error;
  8330.     end
  8331.   else if cur_chr=fi_code then @<Pop the condition stack@>;
  8332.   end
  8333. @ @<Either process \.{\\ifcase} or set |b|...@>=
  8334. case this_if of
  8335. if_char_code, if_cat_code: @<Test if two characters match@>;
  8336. if_int_code, if_dim_code: @<Test relation between integers or dimensions@>;
  8337. if_odd_code: @<Test if an integer is odd@>;
  8338. if_vmode_code: b:=(abs(mode)=vmode);
  8339. if_hmode_code: b:=(abs(mode)=hmode);
  8340. if_mmode_code: b:=(abs(mode)=mmode);
  8341. if_inner_code: b:=(mode<0);
  8342. if_void_code, if_hbox_code, if_vbox_code: @<Test box register status@>;
  8343. ifx_code: @<Test if two tokens match@>;
  8344. if_eof_code: begin scan_four_bit_int; b:=(read_open[cur_val]=closed);
  8345.   end;
  8346. if_true_code: b:=true;
  8347. if_false_code: b:=false;
  8348. if_case_code: @<Select the appropriate case
  8349.   and |return| or |goto common_ending|@>;
  8350. end {there are no other cases}
  8351. @ @<Display the value of |b|@>=
  8352. begin begin_diagnostic;
  8353. if b then print("{true}")@+else print("{false}");
  8354. end_diagnostic(false);
  8355. @ Here we use the fact that |"<"|, |"="|, and |">"| are consecutive ASCII
  8356. codes.
  8357. @^ASCII code@>
  8358. @<Test relation between integers or dimensions@>=
  8359. begin if this_if=if_int_code then scan_int@+else scan_normal_dimen;
  8360. n:=cur_val; @<Get the next non-blank non-call...@>;
  8361. if (cur_tok>=other_token+"<")and(cur_tok<=other_token+">") then
  8362.   r:=cur_tok-other_token
  8363. else  begin print_err("Missing = inserted for ");
  8364. @.Missing = inserted@>
  8365.   print_cmd_chr(if_test,this_if);
  8366.   help1("I was expecting to see `<', `=', or `>'. Didn't.");
  8367.   back_error; r:="=";
  8368.   end;
  8369. if this_if=if_int_code then scan_int@+else scan_normal_dimen;
  8370. case r of
  8371. "<": b:=(n<cur_val);
  8372. "=": b:=(n=cur_val);
  8373. ">": b:=(n>cur_val);
  8374. @ @<Test if an integer is odd@>=
  8375. begin scan_int; b:=odd(cur_val);
  8376. @ @<Test box register status@>=
  8377. begin scan_eight_bit_int; p:=box(cur_val);
  8378. if this_if=if_void_code then b:=(p=null)
  8379. else if p=null then b:=false
  8380. else if this_if=if_hbox_code then b:=(type(p)=hlist_node)
  8381. else b:=(type(p)=vlist_node);
  8382. @ An active character will be treated as category 13 following
  8383. \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
  8384. active characters have the smallest tokens, among all control sequences.
  8385. @d get_x_token_or_active_char==@t@>@;
  8386.   begin get_x_token;
  8387.   if cur_cmd=relax then if cur_chr=no_expand_flag then
  8388.     begin cur_cmd:=active_char;
  8389.     cur_chr:=cur_tok-cs_token_flag-active_base;
  8390.     end;
  8391.   end
  8392. @<Test if two characters match@>=
  8393. begin get_x_token_or_active_char;
  8394. if (cur_cmd>active_char)or(cur_chr>255) then {not a character}
  8395.   begin m:=relax; n:=256;
  8396.   end
  8397. else  begin m:=cur_cmd; n:=cur_chr;
  8398.   end;
  8399. get_x_token_or_active_char;
  8400. if (cur_cmd>active_char)or(cur_chr>255) then
  8401.   begin cur_cmd:=relax; cur_chr:=256;
  8402.   end;
  8403. if this_if=if_char_code then b:=(n=cur_chr)@+else b:=(m=cur_cmd);
  8404. @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
  8405. or \\{outer} and the other isn't, even though the texts of the macros are
  8406. the same.
  8407. We need to reset |scanner_status|, since \.{\\outer} control sequences
  8408. are allowed, but we might be scanning a macro definition or preamble.
  8409. @<Test if two tokens match@>=
  8410. begin save_scanner_status:=scanner_status; scanner_status:=normal;
  8411. get_next; n:=cur_cs; p:=cur_cmd; q:=cur_chr;
  8412. get_next; if cur_cmd<>p then b:=false
  8413. else if cur_cmd<call then b:=(cur_chr=q)
  8414. else @<Test if two macro texts match@>;
  8415. scanner_status:=save_scanner_status;
  8416. @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
  8417. different in examples like this:
  8418. $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
  8419.   {}\\def\\a\{\\c\}&
  8420.   {}\\def\\c\{\}\cr
  8421.   {}\\def\\b\{\\d\}&
  8422.   {}\\def\\d\{\}\cr}}$$
  8423. @<Test if two macro texts match@>=
  8424. begin p:=link(cur_chr); q:=link(equiv(n)); {omit reference counts}
  8425. if p=q then b:=true
  8426. else begin while (p<>null)and(q<>null) do
  8427.     if info(p)<>info(q) then p:=null
  8428.     else  begin p:=link(p); q:=link(q);
  8429.       end;
  8430.   b:=((p=null)and(q=null));
  8431.   end;
  8432. @ @<Select the appropriate case and |return| or |goto common_ending|@>=
  8433. begin scan_int; n:=cur_val; {|n| is the number of cases to pass}
  8434. if tracing_commands>1 then
  8435.   begin begin_diagnostic; print("{case "); print_int(n); print_char("}");
  8436.   end_diagnostic(false);
  8437.   end;
  8438. while n<>0 do
  8439.   begin pass_text;
  8440.   if cond_ptr=save_cond_ptr then
  8441.     if cur_chr=or_code then decr(n)
  8442.     else goto common_ending
  8443.   else if cur_chr=fi_code then @<Pop the condition stack@>;
  8444.   end;
  8445. change_if_limit(or_code,save_cond_ptr);
  8446. return; {wait for \.{\\or}, \.{\\else}, or \.{\\fi}}
  8447. @ The processing of conditionals is complete except for the following
  8448. code, which is actually part of |expand|. It comes into play when
  8449. \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
  8450. @<Terminate the current conditional and skip to \.{\\fi}@>=
  8451. if cur_chr>if_limit then
  8452.   if if_limit=if_code then insert_relax {condition not yet evaluated}
  8453.   else  begin print_err("Extra "); print_cmd_chr(fi_or_else,cur_chr);
  8454. @.Extra \\or@>
  8455. @.Extra \\else@>
  8456. @.Extra \\fi@>
  8457.     help1("I'm ignoring this; it doesn't match any \if.");
  8458.     error;
  8459.     end
  8460. else  begin while cur_chr<>fi_code do pass_text; {skip to \.{\\fi}}
  8461.   @<Pop the condition stack@>;
  8462.   end
  8463. @* \[29] File names.
  8464. It's time now to fret about file names.  Besides the fact that different
  8465. operating systems treat files in different ways, we must cope with the
  8466. fact that completely different naming conventions are used by different
  8467. groups of people. The following programs show what is required for one
  8468. particular operating system; similar routines for other systems are not
  8469. difficult to devise.
  8470. @^fingers@>
  8471. @^system dependencies@>
  8472. \TeX\ assumes that a file name has three parts: the name proper; its
  8473. ``extension''; and a ``file area'' where it is found in an external file
  8474. system.  The extension of an input file or a write file is assumed to be
  8475. `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
  8476. transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
  8477. metric files that describe characters in the fonts \TeX\ uses; it is
  8478. `\.{.dvi}' on the output files that specify typesetting information; and it
  8479. is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
  8480. The file area can be arbitrary on input files, but files are usually
  8481. output to the user's current area.  If an input file cannot be
  8482. found on the specified area, \TeX\ will look for it on a special system
  8483. area; this special area is intended for commonly used input files like
  8484. \.{webhdr.tex}.
  8485. Simple uses of \TeX\ refer only to file names that have no explicit
  8486. extension or area. For example, a person usually says `\.{\\input} \.{paper}'
  8487. or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
  8488. \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
  8489. names are best, because they make the \TeX\ source files portable;
  8490. whenever a file name consists entirely of letters and digits, it should be
  8491. treated in the same way by all implementations of \TeX. However, users
  8492. need the ability to refer to other files in their environment, especially
  8493. when responding to error messages concerning unopenable files; therefore
  8494. we want to let them use the syntax that appears in their favorite
  8495. operating system.
  8496. @ In order to isolate the system-dependent aspects of file names, the
  8497. @^system dependencies@>
  8498. system-independent parts of \TeX\ are expressed in terms
  8499. of three system-dependent
  8500. procedures called |begin_name|, |more_name|, and |end_name|. In
  8501. essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
  8502. the system-independent driver program does the operations
  8503. $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
  8504. \,|end_name|.$$
  8505. These three procedures communicate with each other via global variables.
  8506. Afterwards the file name will appear in the string pool as three strings
  8507. called |cur_name|\penalty10000\hskip-.05em,
  8508. |cur_area|, and |cur_ext|; the latter two are null (i.e.,
  8509. |""|), unless they were explicitly specified by the user.
  8510. Actually the situation is slightly more complicated, because \TeX\ needs
  8511. to know when the file name ends. The |more_name| routine is a function
  8512. (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
  8513. \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
  8514. returns |false|; or, it returns |true| and the token following $c_n$ is
  8515. something like `\.{\\hbox}' (i.e., not a character). In other words,
  8516. |more_name| is supposed to return |true| unless it is sure that the
  8517. file name has been completely scanned; and |end_name| is supposed to be able
  8518. to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
  8519. whether $|more_name|(c_n)$ returned |true| or |false|.
  8520. @<Glob...@>=
  8521. @!cur_name:str_number; {name of file just scanned}
  8522. @!cur_area:str_number; {file area just scanned, or \.{""}}
  8523. @!cur_ext:str_number; {file extension just scanned, or \.{""}}
  8524. @ The file names we shall deal with for illustrative purposes have the
  8525. following structure:  If the name contains `\.>' or `\.:', the file area
  8526. consists of all characters up to and including the final such character;
  8527. otherwise the file area is null.  If the remaining file name contains
  8528. `\..', the file extension consists of all such characters from the first
  8529. remaining `\..' to the end, otherwise the file extension is null.
  8530. @^system dependencies@>
  8531. We can scan such file names easily by using two global variables that keep track
  8532. of the occurrences of area and extension delimiters:
  8533. @<Glob...@>=
  8534. @!area_delimiter:pool_pointer; {the most recent `\.>' or `\.:', if any}
  8535. @!ext_delimiter:pool_pointer; {the relevant `\..', if any}
  8536. @ Input files that can't be found in the user's area may appear in a standard
  8537. system area called |TEX_area|. Font metric files whose areas are not given
  8538. explicitly are assumed to appear in a standard system area called
  8539. |TEX_font_area|.  These system area names will, of course, vary from place
  8540. to place.
  8541. @^system dependencies@>
  8542. @d TEX_area=="TeXinputs:"
  8543. @.TeXinputs@>
  8544. @d TEX_font_area=="TeXfonts:"
  8545. @.TeXfonts@>
  8546. @ Here now is the first of the system-dependent routines for file name scanning.
  8547. @^system dependencies@>
  8548. @p procedure begin_name;
  8549. begin area_delimiter:=0; ext_delimiter:=0;
  8550. @ And here's the second. The string pool might change as the file name is
  8551. being scanned, since a new \.{\\csname} might be entered; therefore we keep
  8552. |area_delimiter| and |ext_delimiter| relative to the beginning of the current
  8553. string, instead of assigning an absolute address like |pool_ptr| to them.
  8554. @^system dependencies@>
  8555. @p function more_name(@!c:ASCII_code):boolean;
  8556. begin if c=" " then more_name:=false
  8557. else  begin str_room(1); append_char(c); {contribute |c| to the current string}
  8558.   if (c=">")or(c=":") then
  8559.     begin area_delimiter:=cur_length; ext_delimiter:=0;
  8560.     end
  8561.   else if (c=".")and(ext_delimiter=0) then ext_delimiter:=cur_length;
  8562.   more_name:=true;
  8563.   end;
  8564. @ The third.
  8565. @^system dependencies@>
  8566. @p procedure end_name;
  8567. begin if str_ptr+3>max_strings then
  8568.   overflow("number of strings",max_strings-init_str_ptr);
  8569. @:TeX capacity exceeded number of strings}{\quad number of strings@>
  8570. if area_delimiter=0 then cur_area:=""
  8571. else  begin cur_area:=str_ptr;
  8572.   str_start[str_ptr+1]:=str_start[str_ptr]+area_delimiter; incr(str_ptr);
  8573.   end;
  8574. if ext_delimiter=0 then
  8575.   begin cur_ext:=""; cur_name:=make_string;
  8576.   end
  8577. else  begin cur_name:=str_ptr;
  8578.   str_start[str_ptr+1]:=str_start[str_ptr]+ext_delimiter-area_delimiter-1;
  8579.   incr(str_ptr); cur_ext:=make_string;
  8580.   end;
  8581. @ Conversely, here is a routine that takes three strings and prints a file
  8582. name that might have produced them. (The routine is system dependent, because
  8583. some operating systems put the file area last instead of first.)
  8584. @^system dependencies@>
  8585. @<Basic printing...@>=
  8586. procedure print_file_name(@!n,@!a,@!e:integer);
  8587. begin slow_print(a); slow_print(n); slow_print(e);
  8588. @ Another system-dependent routine is needed to convert three internal
  8589. \TeX\ strings
  8590. into the |name_of_file| value that is used to open files. The present code
  8591. allows both lowercase and uppercase letters in the file name.
  8592. @^system dependencies@>
  8593. @d append_to_name(#)==begin c:=#; incr(k);
  8594.   if k<=file_name_size then name_of_file[k]:=xchr[c];
  8595.   end
  8596. @p procedure pack_file_name(@!n,@!a,@!e:str_number);
  8597. var k:integer; {number of positions filled in |name_of_file|}
  8598. @!c: ASCII_code; {character being packed}
  8599. @!j:pool_pointer; {index into |str_pool|}
  8600. begin k:=0;
  8601. for j:=str_start[a] to str_start[a+1]-1 do append_to_name(so(str_pool[j]));
  8602. for j:=str_start[n] to str_start[n+1]-1 do append_to_name(so(str_pool[j]));
  8603. for j:=str_start[e] to str_start[e+1]-1 do append_to_name(so(str_pool[j]));
  8604. if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
  8605. for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
  8606. @ A messier routine is also needed, since format file names must be scanned
  8607. before \TeX's string mechanism has been initialized. We shall use the
  8608. global variable |TEX_format_default| to supply the text for default system areas
  8609. and extensions related to format files.
  8610. @^system dependencies@>
  8611. @d format_default_length=20 {length of the |TEX_format_default| string}
  8612. @d format_area_length=11 {length of its area part}
  8613. @d format_ext_length=4 {length of its `\.{.fmt}' part}
  8614. @d format_extension=".fmt" {the extension, as a \.{WEB} constant}
  8615. @<Glob...@>=
  8616. @!TEX_format_default:packed array[1..format_default_length] of char;
  8617. @ @<Set init...@>=
  8618. TEX_format_default:='TeXformats:plain.fmt';
  8619. @.TeXformats@>
  8620. @.plain@>
  8621. @^system dependencies@>
  8622. @ @<Check the ``constant'' values for consistency@>=
  8623. if format_default_length>file_name_size then bad:=31;
  8624. @ Here is the messy routine that was just mentioned. It sets |name_of_file|
  8625. from the first |n| characters of |TEX_format_default|, followed by
  8626. |buffer[a..b]|, followed by the last |format_ext_length| characters of
  8627. |TEX_format_default|.
  8628. We dare not give error messages here, since \TeX\ calls this routine before
  8629. the |error| routine is ready to roll. Instead, we simply drop excess characters,
  8630. since the error will be detected in another way when a strange file name
  8631. isn't found.
  8632. @^system dependencies@>
  8633. @p procedure pack_buffered_name(@!n:small_number;@!a,@!b:integer);
  8634. var k:integer; {number of positions filled in |name_of_file|}
  8635. @!c: ASCII_code; {character being packed}
  8636. @!j:integer; {index into |buffer| or |TEX_format_default|}
  8637. begin if n+b-a+1+format_ext_length>file_name_size then
  8638.   b:=a+file_name_size-n-1-format_ext_length;
  8639. k:=0;
  8640. for j:=1 to n do append_to_name(xord[TEX_format_default[j]]);
  8641. for j:=a to b do append_to_name(buffer[j]);
  8642. for j:=format_default_length-format_ext_length+1 to format_default_length do
  8643.   append_to_name(xord[TEX_format_default[j]]);
  8644. if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
  8645. for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
  8646. @ Here is the only place we use |pack_buffered_name|. This part of the program
  8647. becomes active when a ``virgin'' \TeX\ is trying to get going, just after
  8648. the preliminary initialization, or when the user is substituting another
  8649. format file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
  8650. contains the first line of input in |buffer[loc..(last-1)]|, where
  8651. |loc<last| and |buffer[loc]<>" "|.
  8652. @<Declare the function called |open_fmt_file|@>=
  8653. function open_fmt_file:boolean;
  8654. label found,exit;
  8655. var j:0..buf_size; {the first space after the format file name}
  8656. begin j:=loc;
  8657. if buffer[loc]="&" then
  8658.   begin incr(loc); j:=loc; buffer[last]:=" ";
  8659.   while buffer[j]<>" " do incr(j);
  8660.   pack_buffered_name(0,loc,j-1); {try first without the system file area}
  8661.   if w_open_in(fmt_file) then goto found;
  8662.   pack_buffered_name(format_area_length,loc,j-1);
  8663.     {now try the system format file area}
  8664.   if w_open_in(fmt_file) then goto found;
  8665.   wake_up_terminal;
  8666.   wterm_ln('Sorry, I can''t find that format;',' will try PLAIN.');
  8667. @.Sorry, I can't find...@>
  8668.   update_terminal;
  8669.   end;
  8670.   {now pull out all the stops: try for the system \.{plain} file}
  8671. pack_buffered_name(format_default_length-format_ext_length,1,0);
  8672. if not w_open_in(fmt_file) then
  8673.   begin wake_up_terminal;
  8674.   wterm_ln('I can''t find the PLAIN format file!');
  8675. @.I can't find PLAIN...@>
  8676. @.plain@>
  8677.   open_fmt_file:=false; return;
  8678.   end;
  8679. found:loc:=j; open_fmt_file:=true;
  8680. exit:end;
  8681. @ Operating systems often make it possible to determine the exact name (and
  8682. possible version number) of a file that has been opened. The following routine,
  8683. which simply makes a \TeX\ string from the value of |name_of_file|, should
  8684. ideally be changed to deduce the full name of file~|f|, which is the file
  8685. most recently opened, if it is possible to do this in a \PASCAL\ program.
  8686. @^system dependencies@>
  8687. This routine might be called after string memory has overflowed, hence
  8688. we dare not use `|str_room|'.
  8689. @p function make_name_string:str_number;
  8690. var k:1..file_name_size; {index into |name_of_file|}
  8691. begin if (pool_ptr+name_length>pool_size)or(str_ptr=max_strings)or
  8692.  (cur_length>0) then
  8693.   make_name_string:="?"
  8694. else  begin for k:=1 to name_length do append_char(xord[name_of_file[k]]);
  8695.   make_name_string:=make_string;
  8696.   end;
  8697. function a_make_name_string(var f:alpha_file):str_number;
  8698. begin a_make_name_string:=make_name_string;
  8699. function b_make_name_string(var f:byte_file):str_number;
  8700. begin b_make_name_string:=make_name_string;
  8701. function w_make_name_string(var f:word_file):str_number;
  8702. begin w_make_name_string:=make_name_string;
  8703. @ Now let's consider the ``driver''
  8704. routines by which \TeX\ deals with file names
  8705. in a system-independent manner.  First comes a procedure that looks for a
  8706. file name in the input by calling |get_x_token| for the information.
  8707. @p procedure scan_file_name;
  8708. label done;
  8709. begin name_in_progress:=true; begin_name;
  8710. @<Get the next non-blank non-call...@>;
  8711. loop@+begin if (cur_cmd>other_char)or(cur_chr>255) then {not a character}
  8712.     begin back_input; goto done;
  8713.     end;
  8714.   if not more_name(cur_chr) then goto done;
  8715.   get_x_token;
  8716.   end;
  8717. done: end_name; name_in_progress:=false;
  8718. @ The global variable |name_in_progress| is used to prevent recursive
  8719. use of |scan_file_name|, since the |begin_name| and other procedures
  8720. communicate via global variables. Recursion would arise only by
  8721. devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
  8722. must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
  8723. @^recursion@>
  8724. from being initiated when a font size specification is being scanned.
  8725. Another global variable, |job_name|, contains the file name that was first
  8726. \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
  8727. and `\.{.fmt}' in the names of \TeX's output files.
  8728. @<Glob...@>=
  8729. @!name_in_progress:boolean; {is a file name being scanned?}
  8730. @!job_name:str_number; {principal file name}
  8731. @!log_opened:boolean; {has the transcript file been opened?}
  8732. @ Initially |job_name=0|; it becomes nonzero as soon as the true name is known.
  8733. We have |job_name=0| if and only if the `\.{log}' file has not been opened,
  8734. except of course for a short time just after |job_name| has become nonzero.
  8735. @<Initialize the output...@>=
  8736. job_name:=0; name_in_progress:=false; log_opened:=false;
  8737. @ Here is a routine that manufactures the output file names, assuming that
  8738. |job_name<>0|. It ignores and changes the current settings of |cur_area|
  8739. and |cur_ext|.
  8740. @d pack_cur_name==pack_file_name(cur_name,cur_area,cur_ext)
  8741. @p procedure pack_job_name(@!s:str_number); {|s = ".log"|, |".dvi"|, or
  8742.   |format_extension|}
  8743. begin cur_area:=""; cur_ext:=s;
  8744. cur_name:=job_name; pack_cur_name;
  8745. @ If some trouble arises when \TeX\ tries to open a file, the following
  8746. routine calls upon the user to supply another file name. Parameter~|s|
  8747. is used in the error message to identify the type of file; parameter~|e|
  8748. is the default extension if none is given. Upon exit from the routine,
  8749. variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
  8750. ready for another attempt at file opening.
  8751. @p procedure prompt_file_name(@!s,@!e:str_number);
  8752. label done;
  8753. var k:0..buf_size; {index into |buffer|}
  8754. begin if interaction=scroll_mode then wake_up_terminal;
  8755. if s="input file name" then print_err("I can't find file `")
  8756. @.I can't find file x@>
  8757. else print_err("I can't write on file `");
  8758. @.I can't write on file x@>
  8759. print_file_name(cur_name,cur_area,cur_ext); print("'.");
  8760. if e=".tex" then show_context;
  8761. print_nl("Please type another "); print(s);
  8762. @.Please type...@>
  8763. if interaction<scroll_mode then
  8764.   fatal_error("*** (job aborted, file error in nonstop mode)");
  8765. @.job aborted, file error...@>
  8766. clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
  8767. if cur_ext="" then cur_ext:=e;
  8768. pack_cur_name;
  8769. @ @<Scan file name in the buffer@>=
  8770. begin begin_name; k:=first;
  8771. while (buffer[k]=" ")and(k<last) do incr(k);
  8772. loop@+  begin if k=last then goto done;
  8773.   if not more_name(buffer[k]) then goto done;
  8774.   incr(k);
  8775.   end;
  8776. done:end_name;
  8777. @ Here's an example of how these conventions are used. Whenever it is time to
  8778. ship out a box of stuff, we shall use the macro |ensure_dvi_open|.
  8779. @d ensure_dvi_open==if output_file_name=0 then
  8780.   begin if job_name=0 then open_log_file;
  8781.   pack_job_name(".dvi");
  8782.   while not b_open_out(dvi_file) do
  8783.     prompt_file_name("file name for output",".dvi");
  8784.   output_file_name:=b_make_name_string(dvi_file);
  8785.   end
  8786. @<Glob...@>=
  8787. @!dvi_file: byte_file; {the device-independent output goes here}
  8788. @!output_file_name: str_number; {full name of the output file}
  8789. @!log_name:str_number; {full name of the log file}
  8790. @ @<Initialize the output...@>=output_file_name:=0;
  8791. @ The |open_log_file| routine is used to open the transcript file and to help
  8792. it catch up to what has previously been printed on the terminal.
  8793. @p procedure open_log_file;
  8794. var old_setting:0..max_selector; {previous |selector| setting}
  8795. @!k:0..buf_size; {index into |months| and |buffer|}
  8796. @!l:0..buf_size; {end of first input line}
  8797. @!months:packed array [1..36] of char; {abbreviations of month names}
  8798. begin old_setting:=selector;
  8799. if job_name=0 then job_name:="texput";
  8800. @.texput@>
  8801. pack_job_name(".log");
  8802. while not a_open_out(log_file) do @<Try to get a different log file name@>;
  8803. log_name:=a_make_name_string(log_file);
  8804. selector:=log_only; log_opened:=true;
  8805. @<Print the banner line, including the date and time@>;
  8806. input_stack[input_ptr]:=cur_input; {make sure bottom level is in memory}
  8807. print_nl("**");
  8808. @.**@>
  8809. l:=input_stack[0].limit_field; {last position of first line}
  8810. if buffer[l]=end_line_char then decr(l);
  8811. for k:=1 to l do print(buffer[k]);
  8812. print_ln; {now the transcript file contains the first line of input}
  8813. selector:=old_setting+2; {|log_only| or |term_and_log|}
  8814. @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
  8815. unable to print error messages or even to |show_context|.
  8816. The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
  8817. routine will not be invoked because |log_opened| will be false.
  8818. The normal idea of |batch_mode| is that nothing at all should be written
  8819. on the terminal. However, in the unusual case that
  8820. no log file could be opened, we make an exception and allow
  8821. an explanatory message to be seen.
  8822. Incidentally, the program always refers to the log file as a `\.{transcript
  8823. file}', because some systems cannot use the extension `\.{.log}' for
  8824. this file.
  8825. @<Try to get a different log file name@>=
  8826. begin selector:=term_only;
  8827. prompt_file_name("transcript file name",".log");
  8828. @ @<Print the banner...@>=
  8829. begin wlog(banner);
  8830. slow_print(format_ident); print("  ");
  8831. print_int(day); print_char(" ");
  8832. months:='JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC';
  8833. for k:=3*month-2 to 3*month do wlog(months[k]);
  8834. print_char(" "); print_int(year); print_char(" ");
  8835. print_two(time div 60); print_char(":"); print_two(time mod 60);
  8836. @ Let's turn now to the procedure that is used to initiate file reading
  8837. when an `\.{\\input}' command is being processed.
  8838. @p procedure start_input; {\TeX\ will \.{\\input} something}
  8839. label done;
  8840. begin scan_file_name; {set |cur_name| to desired file name}
  8841. if cur_ext="" then cur_ext:=".tex";
  8842. pack_cur_name;
  8843. loop@+  begin begin_file_reading; {set up |cur_file| and new level of input}
  8844.   if a_open_in(cur_file) then goto done;
  8845.   if cur_area="" then
  8846.     begin pack_file_name(cur_name,TEX_area,cur_ext);
  8847.     if a_open_in(cur_file) then goto done;
  8848.     end;
  8849.   end_file_reading; {remove the level that didn't work}
  8850.   prompt_file_name("input file name",".tex");
  8851.   end;
  8852. done: name:=a_make_name_string(cur_file);
  8853. if job_name=0 then
  8854.   begin job_name:=cur_name; open_log_file;
  8855.   end; {|open_log_file| doesn't |show_context|, so |limit|
  8856.     and |loc| needn't be set to meaningful values yet}
  8857. if term_offset+length(name)>max_print_line-2 then print_ln
  8858. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  8859. print_char("("); incr(open_parens); slow_print(name); update_terminal;
  8860. state:=new_line;
  8861. if name=str_ptr-1 then {we can conserve string pool space now}
  8862.   begin flush_string; name:=cur_name;
  8863.   end;
  8864. @<Read the first line of the new file@>;
  8865. @ Here we have to remember to tell the |input_ln| routine not to
  8866. start with a |get|. If the file is empty, it is considered to
  8867. contain a single blank line.
  8868. @^system dependencies@>
  8869. @^empty line at end of file@>
  8870. @<Read the first line...@>=
  8871. begin line:=1;
  8872. if input_ln(cur_file,false) then do_nothing;
  8873. firm_up_the_line;
  8874. if end_line_char_inactive then decr(limit)
  8875. else  buffer[limit]:=end_line_char;
  8876. first:=limit+1; loc:=start;
  8877. @* \[30] Font metric data.
  8878. \TeX\ gets its knowledge about fonts from font metric files, also called
  8879. \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
  8880. but other programs know about them too.
  8881. @:TFM files}{\.{TFM} files@>
  8882. @^font metric files@>
  8883. The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
  8884. Since the number of bytes is always a multiple of 4, we could
  8885. also regard the file as a sequence of 32-bit words, but \TeX\ uses the
  8886. byte interpretation. The format of \.{TFM} files was designed by
  8887. Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
  8888. @^Ramshaw, Lyle Harold@>
  8889. of information in a compact but useful form.
  8890. @<Glob...@>=
  8891. @!tfm_file:byte_file;
  8892. @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
  8893. integers that give the lengths of the various subsequent portions
  8894. of the file. These twelve integers are, in order:
  8895. $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
  8896. |lf|&length of the entire file, in words;\cr
  8897. |lh|&length of the header data, in words;\cr
  8898. |bc|&smallest character code in the font;\cr
  8899. |ec|&largest character code in the font;\cr
  8900. |nw|&number of words in the width table;\cr
  8901. |nh|&number of words in the height table;\cr
  8902. |nd|&number of words in the depth table;\cr
  8903. |ni|&number of words in the italic correction table;\cr
  8904. |nl|&number of words in the lig/kern table;\cr
  8905. |nk|&number of words in the kern table;\cr
  8906. |ne|&number of words in the extensible character table;\cr
  8907. |np|&number of font parameter words.\cr}}$$
  8908. They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
  8909. $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
  8910. Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
  8911. and as few as 0 characters (if |bc=ec+1|).
  8912. Incidentally, when two or more 8-bit bytes are combined to form an integer of
  8913. 16 or more bits, the most significant bytes appear first in the file.
  8914. This is called BigEndian order.
  8915. @!@^BigEndian order@>
  8916. @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
  8917. arrays having the informal specification
  8918. $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
  8919. \vbox{\halign{\hfil\\{#}&$\,:\,$\arr#\hfil\cr
  8920. header&|[0..lh-1]@t\\{stuff}@>|\cr
  8921. char\_info&|[bc..ec]char_info_word|\cr
  8922. width&|[0..nw-1]fix_word|\cr
  8923. height&|[0..nh-1]fix_word|\cr
  8924. depth&|[0..nd-1]fix_word|\cr
  8925. italic&|[0..ni-1]fix_word|\cr
  8926. lig\_kern&|[0..nl-1]lig_kern_command|\cr
  8927. kern&|[0..nk-1]fix_word|\cr
  8928. exten&|[0..ne-1]extensible_recipe|\cr
  8929. param&|[1..np]fix_word|\cr}}$$
  8930. The most important data type used here is a |@!fix_word|, which is
  8931. a 32-bit representation of a binary fraction. A |fix_word| is a signed
  8932. quantity, with the two's complement of the entire word used to represent
  8933. negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
  8934. binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
  8935. the smallest is $-2048$. We will see below, however, that all but two of
  8936. the |fix_word| values must lie between $-16$ and $+16$.
  8937. @ The first data array is a block of header information, which contains
  8938. general facts about the font. The header must contain at least two words,
  8939. |header[0]| and |header[1]|, whose meaning is explained below.
  8940. Additional header information of use to other software routines might
  8941. also be included, but \TeX82 does not need to know about such details.
  8942. For example, 16 more words of header information are in use at the Xerox
  8943. Palo Alto Research Center; the first ten specify the character coding
  8944. scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
  8945. give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
  8946. last gives the ``face byte.'' The program that converts \.{DVI} files
  8947. to Xerox printing format gets this information by looking at the \.{TFM}
  8948. file, which it needs to read anyway because of other information that
  8949. is not explicitly repeated in \.{DVI}~format.
  8950. \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
  8951. the \.{DVI} output file. Later on when the \.{DVI} file is printed,
  8952. possibly on another computer, the actual font that gets used is supposed
  8953. to have a check sum that agrees with the one in the \.{TFM} file used by
  8954. \TeX. In this way, users will be warned about potential incompatibilities.
  8955. (However, if the check sum is zero in either the font file or the \.{TFM}
  8956. file, no check is made.)  The actual relation between this check sum and
  8957. the rest of the \.{TFM} file is not important; the check sum is simply an
  8958. identification number with the property that incompatible fonts almost
  8959. always have distinct check sums.
  8960. @^check sum@>
  8961. \yskip\hang|header[1]| is a |fix_word| containing the design size of
  8962. the font, in units of \TeX\ points. This number must be at least 1.0; it is
  8963. fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
  8964. font, i.e., a font that was designed to look best at a 10-point size,
  8965. whatever that really means. When a \TeX\ user asks for a font
  8966. `\.{at} $\delta$ \.{pt}', the effect is to override the design size
  8967. and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
  8968. of the points in the font image by a factor of $\delta$ divided by the
  8969. design size.  {\sl All other dimensions in the\/ \.{TFM} file are
  8970. |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
  8971. |param[1]| (which denotes the slant ratio). Thus, for example, the value
  8972. of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
  8973. $2^{20}=1.0$, since many fonts have a design size equal to one em.
  8974. The other dimensions must be less than 16 design-size units in absolute
  8975. value; thus, |header[1]| and |param[1]| are the only |fix_word|
  8976. entries in the whole \.{TFM} file whose first byte might be something
  8977. besides 0 or 255.
  8978. @ Next comes the |char_info| array, which contains one |@!char_info_word|
  8979. per character. Each word in this part of the file contains six fields
  8980. packed into four bytes as follows.
  8981. \yskip\hang first byte: |@!width_index| (8 bits)\par
  8982. \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
  8983.   (4~bits)\par
  8984. \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
  8985.   (2~bits)\par
  8986. \hang fourth byte: |@!remainder| (8 bits)\par
  8987. \yskip\noindent
  8988. The actual width of a character is \\{width}|[width_index]|, in design-size
  8989. units; this is a device for compressing information, since many characters
  8990. have the same width. Since it is quite common for many characters
  8991. to have the same height, depth, or italic correction, the \.{TFM} format
  8992. imposes a limit of 16 different heights, 16 different depths, and
  8993. 64 different italic corrections.
  8994. @!@^italic correction@>
  8995. The italic correction of a character has two different uses.
  8996. (a)~In ordinary text, the italic correction is added to the width only if
  8997. the \TeX\ user specifies `\.{\\/}' after the character.
  8998. (b)~In math formulas, the italic correction is always added to the width,
  8999. except with respect to the positioning of subscripts.
  9000. Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
  9001. \\{italic}[0]=0$ should always hold, so that an index of zero implies a
  9002. value of zero.  The |width_index| should never be zero unless the
  9003. character does not exist in the font, since a character is valid if and
  9004. only if it lies between |bc| and |ec| and has a nonzero |width_index|.
  9005. @ The |tag| field in a |char_info_word| has four values that explain how to
  9006. interpret the |remainder| field.
  9007. \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
  9008. \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
  9009. program starting at position |remainder| in the |lig_kern| array.\par
  9010. \hang|tag=2| (|list_tag|) means that this character is part of a chain of
  9011. characters of ascending sizes, and not the largest in the chain.  The
  9012. |remainder| field gives the character code of the next larger character.\par
  9013. \hang|tag=3| (|ext_tag|) means that this character code represents an
  9014. extensible character, i.e., a character that is built up of smaller pieces
  9015. so that it can be made arbitrarily large. The pieces are specified in
  9016. |@!exten[remainder]|.\par
  9017. \yskip\noindent
  9018. Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
  9019. unless they are used in special circumstances in math formulas. For example,
  9020. the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
  9021. operation looks for both |list_tag| and |ext_tag|.
  9022. @d no_tag=0 {vanilla character}
  9023. @d lig_tag=1 {character has a ligature/kerning program}
  9024. @d list_tag=2 {character has a successor in a charlist}
  9025. @d ext_tag=3 {character is extensible}
  9026. @ The |lig_kern| array contains instructions in a simple programming language
  9027. that explains what to do for special letter pairs. Each word in this array is a
  9028. |@!lig_kern_command| of four bytes.
  9029. \yskip\hang first byte: |skip_byte|, indicates that this is the final program
  9030.   step if the byte is 128 or more, otherwise the next step is obtained by
  9031.   skipping this number of intervening steps.\par
  9032. \hang second byte: |next_char|, ``if |next_char| follows the current character,
  9033.   then perform the operation and stop, otherwise continue.''\par
  9034. \hang third byte: |op_byte|, indicates a ligature step if less than~128,
  9035.   a kern step otherwise.\par
  9036. \hang fourth byte: |remainder|.\par
  9037. \yskip\noindent
  9038. In a kern step, an
  9039. additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
  9040. between the current character and |next_char|. This amount is
  9041. often negative, so that the characters are brought closer together
  9042. by kerning; but it might be positive.
  9043. There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
  9044. $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
  9045. |remainder| is inserted between the current character and |next_char|;
  9046. then the current character is deleted if $b=0$, and |next_char| is
  9047. deleted if $c=0$; then we pass over $a$~characters to reach the next
  9048. current character (which may have a ligature/kerning program of its own).
  9049. If the very first instruction of the |lig_kern| array has |skip_byte=255|,
  9050. the |next_char| byte is the so-called right boundary character of this font;
  9051. the value of |next_char| need not lie between |bc| and~|ec|.
  9052. If the very last instruction of the |lig_kern| array has |skip_byte=255|,
  9053. there is a special ligature/kerning program for a left boundary character,
  9054. beginning at location |256*op_byte+remainder|.
  9055. The interpretation is that \TeX\ puts implicit boundary characters
  9056. before and after each consecutive string of characters from the same font.
  9057. These implicit characters do not appear in the output, but they can affect
  9058. ligatures and kerning.
  9059. If the very first instruction of a character's |lig_kern| program has
  9060. |skip_byte>128|, the program actually begins in location
  9061. |256*op_byte+remainder|. This feature allows access to large |lig_kern|
  9062. arrays, because the first instruction must otherwise
  9063. appear in a location |<=255|.
  9064. Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
  9065. the condition
  9066. $$\hbox{|256*op_byte+remainder<nl|.}$$
  9067. If such an instruction is encountered during
  9068. normal program execution, it denotes an unconditional halt; no ligature
  9069. or kerning command is performed.
  9070. @d stop_flag==qi(128) {value indicating `\.{STOP}' in a lig/kern program}
  9071. @d kern_flag==qi(128) {op code for a kern step}
  9072. @d skip_byte(#)==#.b0
  9073. @d next_char(#)==#.b1
  9074. @d op_byte(#)==#.b2
  9075. @d rem_byte(#)==#.b3
  9076. @ Extensible characters are specified by an |@!extensible_recipe|, which
  9077. consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
  9078. order). These bytes are the character codes of individual pieces used to
  9079. build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
  9080. present in the built-up result. For example, an extensible vertical line is
  9081. like an extensible bracket, except that the top and bottom pieces are missing.
  9082. Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
  9083. if the piece isn't present. Then the extensible characters have the form
  9084. $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
  9085. in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
  9086. The width of the extensible character is the width of $R$; and the
  9087. height-plus-depth is the sum of the individual height-plus-depths of the
  9088. components used, since the pieces are butted together in a vertical list.
  9089. @d ext_top(#)==#.b0 {|top| piece in a recipe}
  9090. @d ext_mid(#)==#.b1 {|mid| piece in a recipe}
  9091. @d ext_bot(#)==#.b2 {|bot| piece in a recipe}
  9092. @d ext_rep(#)==#.b3 {|rep| piece in a recipe}
  9093. @ The final portion of a \.{TFM} file is the |param| array, which is another
  9094. sequence of |fix_word| values.
  9095. \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
  9096. to help position accents. For example, |slant=.25| means that when you go
  9097. up one unit, you also go .25 units to the right. The |slant| is a pure
  9098. number; it's the only |fix_word| other than the design size itself that is
  9099. not scaled by the design size.
  9100. \hang|param[2]=space| is the normal spacing between words in text.
  9101. Note that character |" "| in the font need not have anything to do with
  9102. blank spaces.
  9103. \hang|param[3]=space_stretch| is the amount of glue stretching between words.
  9104. \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
  9105. \hang|param[5]=x_height| is the size of one ex in the font; it is also
  9106. the height of letters for which accents don't have to be raised or lowered.
  9107. \hang|param[6]=quad| is the size of one em in the font.
  9108. \hang|param[7]=extra_space| is the amount added to |param[2]| at the
  9109. ends of sentences.
  9110. \yskip\noindent
  9111. If fewer than seven parameters are present, \TeX\ sets the missing parameters
  9112. to zero. Fonts used for math symbols are required to have
  9113. additional parameter information, which is explained later.
  9114. @d slant_code=1
  9115. @d space_code=2
  9116. @d space_stretch_code=3
  9117. @d space_shrink_code=4
  9118. @d x_height_code=5
  9119. @d quad_code=6
  9120. @d extra_space_code=7
  9121. @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
  9122. about lots of fonts, it stores most of the data in a large array called
  9123. |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
  9124. data gets converted into |scaled| entries, while everything else goes into
  9125. words of type |four_quarters|.
  9126. When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
  9127. to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
  9128. |eqtb| location of a ``frozen'' control sequence that will always select
  9129. the font.
  9130. @<Types...@>=
  9131. @!internal_font_number=font_base..font_max; {|font| in a |char_node|}
  9132. @!font_index=0..font_mem_size; {index into |font_info|}
  9133. @ Here now is the (rather formidable) array of font arrays.
  9134. @d non_char==qi(256) {a |halfword| code that can't match a real character}
  9135. @d non_address=0 {a spurious |bchar_label|}
  9136. @<Glob...@>=
  9137. @!font_info:array[font_index] of memory_word;
  9138.   {the big collection of font data}
  9139. @!fmem_ptr:font_index; {first unused word of |font_info|}
  9140. @!font_ptr:internal_font_number; {largest internal font number in use}
  9141. @!font_check:array[internal_font_number] of four_quarters; {check sum}
  9142. @!font_size:array[internal_font_number] of scaled; {``at'' size}
  9143. @!font_dsize:array[internal_font_number] of scaled; {``design'' size}
  9144. @!font_params:array[internal_font_number] of font_index; {how many font
  9145.   parameters are present}
  9146. @!font_name:array[internal_font_number] of str_number; {name of the font}
  9147. @!font_area:array[internal_font_number] of str_number; {area of the font}
  9148. @!font_bc:array[internal_font_number] of eight_bits;
  9149.   {beginning (smallest) character code}
  9150. @!font_ec:array[internal_font_number] of eight_bits;
  9151.   {ending (largest) character code}
  9152. @!font_glue:array[internal_font_number] of pointer;
  9153.   {glue specification for interword space, |null| if not allocated}
  9154. @!font_used:array[internal_font_number] of boolean;
  9155.   {has a character from this font actually appeared in the output?}
  9156. @!hyphen_char:array[internal_font_number] of integer;
  9157.   {current \.{\\hyphenchar} values}
  9158. @!skew_char:array[internal_font_number] of integer;
  9159.   {current \.{\\skewchar} values}
  9160. @!bchar_label:array[internal_font_number] of font_index;
  9161.   {start of |lig_kern| program for left boundary character,
  9162.   |non_address| if there is none}
  9163. @!font_bchar:array[internal_font_number] of min_quarterword..non_char;
  9164.   {right boundary character, |non_char| if there is none}
  9165. @!font_false_bchar:array[internal_font_number] of min_quarterword..non_char;
  9166.   {|font_bchar| if it doesn't exist in the font, otherwise |non_char|}
  9167. @ Besides the arrays just enumerated, we have directory arrays that make it
  9168. easy to get at the individual entries in |font_info|. For example, the
  9169. |char_info| data for character |c| in font |f| will be in
  9170. |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
  9171. part of this word (the |b0| field), the width of the character is
  9172. |font_info[width_base[f]+w].sc|. (These formulas assume that
  9173. |min_quarterword| has already been added to |c| and to |w|, since \TeX\
  9174. stores its quarterwords that way.)
  9175. @<Glob...@>=
  9176. @!char_base:array[internal_font_number] of integer;
  9177.   {base addresses for |char_info|}
  9178. @!width_base:array[internal_font_number] of integer;
  9179.   {base addresses for widths}
  9180. @!height_base:array[internal_font_number] of integer;
  9181.   {base addresses for heights}
  9182. @!depth_base:array[internal_font_number] of integer;
  9183.   {base addresses for depths}
  9184. @!italic_base:array[internal_font_number] of integer;
  9185.   {base addresses for italic corrections}
  9186. @!lig_kern_base:array[internal_font_number] of integer;
  9187.   {base addresses for ligature/kerning programs}
  9188. @!kern_base:array[internal_font_number] of integer;
  9189.   {base addresses for kerns}
  9190. @!exten_base:array[internal_font_number] of integer;
  9191.   {base addresses for extensible recipes}
  9192. @!param_base:array[internal_font_number] of integer;
  9193.   {base addresses for font parameters}
  9194. @ @<Set init...@>=
  9195. for k:=font_base to font_max do font_used[k]:=false;
  9196. @ \TeX\ always knows at least one font, namely the null font. It has no
  9197. characters, and its seven parameters are all equal to zero.
  9198. @<Initialize table...@>=
  9199. font_ptr:=null_font; fmem_ptr:=7;
  9200. font_name[null_font]:="nullfont"; font_area[null_font]:="";
  9201. hyphen_char[null_font]:="-"; skew_char[null_font]:=-1;
  9202. bchar_label[null_font]:=non_address;
  9203. font_bchar[null_font]:=non_char; font_false_bchar[null_font]:=non_char;
  9204. font_bc[null_font]:=1; font_ec[null_font]:=0;
  9205. font_size[null_font]:=0; font_dsize[null_font]:=0;
  9206. char_base[null_font]:=0; width_base[null_font]:=0;
  9207. height_base[null_font]:=0; depth_base[null_font]:=0;
  9208. italic_base[null_font]:=0; lig_kern_base[null_font]:=0;
  9209. kern_base[null_font]:=0; exten_base[null_font]:=0;
  9210. font_glue[null_font]:=null; font_params[null_font]:=7;
  9211. param_base[null_font]:=-1;
  9212. for k:=0 to 6 do font_info[k].sc:=0;
  9213. @ @<Put each...@>=
  9214. primitive("nullfont",set_font,null_font);
  9215. @!@:null_font_}{\.{\\nullfont} primitive@>
  9216. text(frozen_null_font):="nullfont"; eqtb[frozen_null_font]:=eqtb[cur_val];
  9217. @ Of course we want to define macros that suppress the detail of how font
  9218. information is actually packed, so that we don't have to write things like
  9219. $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
  9220. too often. The \.{WEB} definitions here make |char_info(f)(c)| the
  9221. |four_quarters| word of font information corresponding to character
  9222. |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
  9223. the character's width; hence the long formula above is at least
  9224. abbreviated to
  9225. $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
  9226. Usually, of course, we will fetch |q| first and look at several of its
  9227. fields at the same time.
  9228. The italic correction of a character will be denoted by
  9229. |char_italic(f)(q)|, so it is analogous to |char_width|.  But we will get
  9230. at the height and depth in a slightly different way, since we usually want
  9231. to compute both height and depth if we want either one.  The value of
  9232. |height_depth(q)| will be the 8-bit quantity
  9233. $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
  9234. will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
  9235. depth of the character |c| for which |q=char_info(f)(c)|. Got that?
  9236. The tag field will be called |char_tag(q)|; the remainder byte will be
  9237. called |rem_byte(q)|, using a macro that we have already defined above.
  9238. Access to a character's |width|, |height|, |depth|, and |tag| fields is
  9239. part of \TeX's inner loop, so we want these macros to produce code that is
  9240. as fast as possible under the circumstances.
  9241. @^inner loop@>
  9242. @d char_info_end(#)==#].qqqq
  9243. @d char_info(#)==font_info[char_base[#]+char_info_end
  9244. @d char_width_end(#)==#.b0].sc
  9245. @d char_width(#)==font_info[width_base[#]+char_width_end
  9246. @d char_exists(#)==(#.b0>min_quarterword)
  9247. @d char_italic_end(#)==(qo(#.b2)) div 4].sc
  9248. @d char_italic(#)==font_info[italic_base[#]+char_italic_end
  9249. @d height_depth(#)==qo(#.b1)
  9250. @d char_height_end(#)==(#) div 16].sc
  9251. @d char_height(#)==font_info[height_base[#]+char_height_end
  9252. @d char_depth_end(#)==(#) mod 16].sc
  9253. @d char_depth(#)==font_info[depth_base[#]+char_depth_end
  9254. @d char_tag(#)==((qo(#.b2)) mod 4)
  9255. @ The global variable |null_character| is set up to be a word of
  9256. |char_info| for a character that doesn't exist. Such a word provides a
  9257. convenient way to deal with erroneous situations.
  9258. @<Glob...@>=
  9259. @!null_character:four_quarters; {nonexistent character information}
  9260. @ @<Set init...@>=
  9261. null_character.b0:=min_quarterword; null_character.b1:=min_quarterword;
  9262. null_character.b2:=min_quarterword; null_character.b3:=min_quarterword;
  9263. @ Here are some macros that help process ligatures and kerns.
  9264. We write |char_kern(f)(j)| to find the amount of kerning specified by
  9265. kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
  9266. with a ligature/kern program, the first instruction of that program is either
  9267. |i=font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
  9268. depending on whether or not |skip_byte(i)<=stop_flag|.
  9269. The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
  9270. that do not do local optimization.
  9271. @^system dependencies@>
  9272. @d char_kern_end(#)==256*op_byte(#)+rem_byte(#)].sc
  9273. @d char_kern(#)==font_info[kern_base[#]+char_kern_end
  9274. @d kern_base_offset==256*(128+min_quarterword)
  9275. @d lig_kern_start(#)==lig_kern_base[#]+rem_byte {beginning of lig/kern program}
  9276. @d lig_kern_restart_end(#)==256*op_byte(#)+rem_byte(#)+32768-kern_base_offset
  9277. @d lig_kern_restart(#)==lig_kern_base[#]+lig_kern_restart_end
  9278. @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
  9279. @d param_end(#)==param_base[#]].sc
  9280. @d param(#)==font_info[#+param_end
  9281. @d slant==param(slant_code) {slant to the right, per unit distance upward}
  9282. @d space==param(space_code) {normal space between words}
  9283. @d space_stretch==param(space_stretch_code) {stretch between words}
  9284. @d space_shrink==param(space_shrink_code) {shrink between words}
  9285. @d x_height==param(x_height_code) {one ex}
  9286. @d quad==param(quad_code) {one em}
  9287. @d extra_space==param(extra_space_code) {additional space at end of sentence}
  9288. @<The em width for |cur_font|@>=quad(cur_font)
  9289. @ @<The x-height for |cur_font|@>=x_height(cur_font)
  9290. @ \TeX\ checks the information of a \.{TFM} file for validity as the
  9291. file is being read in, so that no further checks will be needed when
  9292. typesetting is going on. The somewhat tedious subroutine that does this
  9293. is called |read_font_info|. It has four parameters: the user font
  9294. identifier~|u|, the file name and area strings |nom| and |aire|, and the
  9295. ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
  9296. to be applied to the design size; |s=-1000| is the normal case.
  9297. Otherwise |s| will be substituted for the design size; in this
  9298. case, |s| must be positive and less than $2048\rm\,pt$
  9299. (i.e., it must be less than $2^{27}$ when considered as an integer).
  9300. The subroutine opens and closes a global file variable called |tfm_file|.
  9301. It returns the value of the internal font number that was just loaded.
  9302. If an error is detected, an error message is issued and no font
  9303. information is stored; |null_font| is returned in this case.
  9304. @d bad_tfm=11 {label for |read_font_info|}
  9305. @d abort==goto bad_tfm {do this when the \.{TFM} data is wrong}
  9306. @p function read_font_info(@!u:pointer;@!nom,@!aire:str_number;
  9307.   @!s:scaled):internal_font_number; {input a \.{TFM} file}
  9308. label done,bad_tfm,not_found;
  9309. var k:font_index; {index into |font_info|}
  9310. @!file_opened:boolean; {was |tfm_file| successfully opened?}
  9311. @!lf,@!lh,@!bc,@!ec,@!nw,@!nh,@!nd,@!ni,@!nl,@!nk,@!ne,@!np:halfword;
  9312.   {sizes of subfiles}
  9313. @!f:internal_font_number; {the new font's number}
  9314. @!g:internal_font_number; {the number to return}
  9315. @!a,@!b,@!c,@!d:eight_bits; {byte variables}
  9316. @!qw:four_quarters;@!sw:scaled; {accumulators}
  9317. @!bch_label:integer; {left boundary start location, or infinity}
  9318. @!bchar:0..256; {right boundary character, or 256}
  9319. @!z:scaled; {the design size or the ``at'' size}
  9320. @!alpha:integer;@!beta:1..16;
  9321.   {auxiliary quantities used in fixed-point multiplication}
  9322. begin g:=null_font;@/
  9323. @<Read and check the font data; |abort| if the \.{TFM} file is
  9324.   malformed; if there's no room for this font, say so and |goto
  9325.   done|; otherwise |incr(font_ptr)| and |goto done|@>;
  9326. bad_tfm: @<Report that the font won't be loaded@>;
  9327. done: if file_opened then b_close(tfm_file);
  9328. read_font_info:=g;
  9329. @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
  9330. between the \.{TFM} format and a symbolic property-list format
  9331. that can be easily edited. These programs contain extensive
  9332. diagnostic information, so \TeX\ does not have to bother giving
  9333. precise details about why it rejects a particular \.{TFM} file.
  9334. @.TFtoPL@> @.PLtoTF@>
  9335. @d start_font_error_message==print_err("Font "); sprint_cs(u);
  9336.   print_char("="); print_file_name(nom,aire,"");
  9337.   if s>=0 then
  9338.     begin print(" at "); print_scaled(s); print("pt");
  9339.     end
  9340.   else if s<>-1000 then
  9341.     begin print(" scaled "); print_int(-s);
  9342.     end
  9343. @<Report that the font won't be loaded@>=
  9344. start_font_error_message;
  9345. @.Font x=xx not loadable...@>
  9346. if file_opened then print(" not loadable: Bad metric (TFM) file")
  9347. else print(" not loadable: Metric (TFM) file not found");
  9348. help5("I wasn't able to read the size data for this font,")@/
  9349. ("so I will ignore the font specification.")@/
  9350. ("[Wizards can fix TFM files using TFtoPL/PLtoTF.]")@/
  9351. ("You might try inserting a different font spec;")@/
  9352. ("e.g., type `I\font<same font id>=<substitute font name>'.");
  9353. error
  9354. @ @<Read and check...@>=
  9355. @<Open |tfm_file| for input@>;
  9356. @<Read the {\.{TFM}} size fields@>;
  9357. @<Use size fields to allocate font information@>;
  9358. @<Read the {\.{TFM}} header@>;
  9359. @<Read character data@>;
  9360. @<Read box dimensions@>;
  9361. @<Read ligature/kern program@>;
  9362. @<Read extensible character recipes@>;
  9363. @<Read font parameters@>;
  9364. @<Make final adjustments and |goto done|@>
  9365. @ @<Open |tfm_file| for input@>=
  9366. file_opened:=false;
  9367. if aire="" then pack_file_name(nom,TEX_font_area,".tfm")
  9368. else pack_file_name(nom,aire,".tfm");
  9369. if not b_open_in(tfm_file) then abort;
  9370. file_opened:=true
  9371. @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
  9372. thus |eof(tfm_file)| might be true when |read_font_info| refers to
  9373. |tfm_file^| or when it says |get(tfm_file)|. If such circumstances
  9374. cause system error messages, you will have to defeat them somehow,
  9375. for example by defining |fget| to be `\ignorespaces|begin get(tfm_file);|
  9376. |if eof(tfm_file) then abort; end|\unskip'.
  9377. @^system dependencies@>
  9378. @d fget==get(tfm_file)
  9379. @d fbyte==tfm_file^
  9380. @d read_sixteen(#)==begin #:=fbyte;
  9381.   if #>127 then abort;
  9382.   fget; #:=#*@'400+fbyte;
  9383.   end
  9384. @d store_four_quarters(#)==begin fget; a:=fbyte; qw.b0:=qi(a);
  9385.   fget; b:=fbyte; qw.b1:=qi(b);
  9386.   fget; c:=fbyte; qw.b2:=qi(c);
  9387.   fget; d:=fbyte; qw.b3:=qi(d);
  9388.   #:=qw;
  9389.   end
  9390. @ @<Read the {\.{TFM}} size fields@>=
  9391. begin read_sixteen(lf);
  9392. fget; read_sixteen(lh);
  9393. fget; read_sixteen(bc);
  9394. fget; read_sixteen(ec);
  9395. if (bc>ec+1)or(ec>255) then abort;
  9396. if bc>255 then {|bc=256| and |ec=255|}
  9397.   begin bc:=1; ec:=0;
  9398.   end;
  9399. fget; read_sixteen(nw);
  9400. fget; read_sixteen(nh);
  9401. fget; read_sixteen(nd);
  9402. fget; read_sixteen(ni);
  9403. fget; read_sixteen(nl);
  9404. fget; read_sixteen(nk);
  9405. fget; read_sixteen(ne);
  9406. fget; read_sixteen(np);
  9407. if lf<>6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np then abort;
  9408. @ The preliminary settings of the index-offset variables |char_base|,
  9409. |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
  9410. corrected later by subtracting |min_quarterword| from them; and we will
  9411. subtract 1 from |param_base| too. It's best to forget about such anomalies
  9412. until later.
  9413. @<Use size fields to allocate font information@>=
  9414. lf:=lf-6-lh; {|lf| words should be loaded into |font_info|}
  9415. if np<7 then lf:=lf+7-np; {at least seven parameters will appear}
  9416. if (font_ptr=font_max)or(fmem_ptr+lf>font_mem_size) then
  9417.   @<Apologize for not loading the font, |goto done|@>;
  9418. f:=font_ptr+1;
  9419. char_base[f]:=fmem_ptr-bc;
  9420. width_base[f]:=char_base[f]+ec+1;
  9421. height_base[f]:=width_base[f]+nw;
  9422. depth_base[f]:=height_base[f]+nh;
  9423. italic_base[f]:=depth_base[f]+nd;
  9424. lig_kern_base[f]:=italic_base[f]+ni;
  9425. kern_base[f]:=lig_kern_base[f]+nl-kern_base_offset;
  9426. exten_base[f]:=kern_base[f]+kern_base_offset+nk;
  9427. param_base[f]:=exten_base[f]+ne
  9428. @ @<Apologize for not loading...@>=
  9429. begin start_font_error_message;
  9430. print(" not loaded: Not enough room left");
  9431. @.Font x=xx not loaded...@>
  9432. help4("I'm afraid I won't be able to make use of this font,")@/
  9433. ("because my memory for character-size data is too small.")@/
  9434. ("If you're really stuck, ask a wizard to enlarge me.")@/
  9435. ("Or maybe try `I\font<same font id>=<name of loaded font>'.");
  9436. error; goto done;
  9437. @ Only the first two words of the header are needed by \TeX82.
  9438. @<Read the {\.{TFM}} header@>=
  9439. begin if lh<2 then abort;
  9440. store_four_quarters(font_check[f]);
  9441. fget; read_sixteen(z); {this rejects a negative design size}
  9442. fget; z:=z*@'400+fbyte; fget; z:=(z*@'20)+(fbyte div@'20);
  9443. if z<unity then abort;
  9444. while lh>2 do
  9445.   begin fget;fget;fget;fget;decr(lh); {ignore the rest of the header}
  9446.   end;
  9447. font_dsize[f]:=z;
  9448. if s<>-1000 then
  9449.   if s>=0 then z:=s
  9450.   else z:=xn_over_d(z,-s,1000);
  9451. font_size[f]:=z;
  9452. @ @<Read character data@>=
  9453. for k:=fmem_ptr to width_base[f]-1 do
  9454.   begin store_four_quarters(font_info[k].qqqq);
  9455.   if (a>=nw)or(b div @'20>=nh)or(b mod @'20>=nd)or
  9456.     (c div 4>=ni) then abort;
  9457.   case c mod 4 of
  9458.   lig_tag: if d>=nl then abort;
  9459.   ext_tag: if d>=ne then abort;
  9460.   list_tag: @<Check for charlist cycle@>;
  9461.   othercases do_nothing {|no_tag|}
  9462.   endcases;
  9463.   end
  9464. @ We want to make sure that there is no cycle of characters linked together
  9465. by |list_tag| entries, since such a cycle would get \TeX\ into an endless
  9466. loop. If such a cycle exists, the routine here detects it when processing
  9467. the largest character code in the cycle.
  9468. @d check_byte_range(#)==begin if (#<bc)or(#>ec) then abort@+end
  9469. @d current_character_being_worked_on==k+bc-fmem_ptr
  9470. @<Check for charlist cycle@>=
  9471. begin check_byte_range(d);
  9472. while d<current_character_being_worked_on do
  9473.   begin qw:=char_info(f)(d);
  9474.   {N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet}
  9475.   if char_tag(qw)<>list_tag then goto not_found;
  9476.   d:=qo(rem_byte(qw)); {next character on the list}
  9477.   end;
  9478. if d=current_character_being_worked_on then abort; {yes, there's a cycle}
  9479. not_found:end
  9480. @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
  9481. the number
  9482. $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
  9483. b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
  9484. -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
  9485. (No other choices of |a| are allowed, since the magnitude of a number in
  9486. design-size units must be less than 16.)  We want to multiply this
  9487. quantity by the integer~|z|, which is known to be less than $2^{27}$.
  9488. If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
  9489. $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
  9490. 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
  9491. compensate for this later. If |z| has thereby been replaced by
  9492. $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
  9493. $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
  9494. if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
  9495. This calculation must be done exactly, in order to guarantee portability
  9496. of \TeX\ between computers.
  9497. @d store_scaled(#)==begin fget; a:=fbyte; fget; b:=fbyte;
  9498.   fget; c:=fbyte; fget; d:=fbyte;@/
  9499.   sw:=(((((d*z)div@'400)+(c*z))div@'400)+(b*z))div beta;
  9500.   if a=0 then #:=sw@+else if a=255 then #:=sw-alpha@+else abort;
  9501.   end
  9502. @<Read box dimensions@>=
  9503. begin @<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
  9504. for k:=width_base[f] to lig_kern_base[f]-1 do
  9505.   store_scaled(font_info[k].sc);
  9506. if font_info[width_base[f]].sc<>0 then abort; {\\{width}[0] must be zero}
  9507. if font_info[height_base[f]].sc<>0 then abort; {\\{height}[0] must be zero}
  9508. if font_info[depth_base[f]].sc<>0 then abort; {\\{depth}[0] must be zero}
  9509. if font_info[italic_base[f]].sc<>0 then abort; {\\{italic}[0] must be zero}
  9510. @ @<Replace |z|...@>=
  9511. begin alpha:=16;
  9512. while z>=@'40000000 do
  9513.   begin z:=z div 2; alpha:=alpha+alpha;
  9514.   end;
  9515. beta:=256 div alpha; alpha:=alpha*z;
  9516. @ @d check_existence(#)==@t@>@;@/
  9517.   begin check_byte_range(#);
  9518.   qw:=char_info(f)(#); {N.B.: not |qi(#)|}
  9519.   if not char_exists(qw) then abort;
  9520.   end
  9521. @<Read ligature/kern program@>=
  9522. bch_label:=@'77777; bchar:=256;
  9523. if nl>0 then
  9524.   begin for k:=lig_kern_base[f] to kern_base[f]+kern_base_offset-1 do
  9525.     begin store_four_quarters(font_info[k].qqqq);
  9526.     if a>128 then
  9527.       begin if 256*c+d>=nl then abort;
  9528.       if a=255 then if k=lig_kern_base[f] then bchar:=b;
  9529.       end
  9530.     else begin if b<>bchar then check_existence(b);
  9531.       if c<128 then check_existence(d) {check ligature}
  9532.       else if 256*(c-128)+d>=nk then abort; {check kern}
  9533.       if a<128 then if k-lig_kern_base[f]+a+1>=nl then abort;
  9534.       end;
  9535.     end;
  9536.   if a=255 then bch_label:=256*c+d;
  9537.   end;
  9538. for k:=kern_base[f]+kern_base_offset to exten_base[f]-1 do
  9539.   store_scaled(font_info[k].sc);
  9540. @ @<Read extensible character recipes@>=
  9541. for k:=exten_base[f] to param_base[f]-1 do
  9542.   begin store_four_quarters(font_info[k].qqqq);
  9543.   if a<>0 then check_existence(a);
  9544.   if b<>0 then check_existence(b);
  9545.   if c<>0 then check_existence(c);
  9546.   check_existence(d);
  9547.   end
  9548. @ We check to see that the \.{TFM} file doesn't end prematurely; but
  9549. no error message is given for files having more than |lf| words.
  9550. @<Read font parameters@>=
  9551. begin for k:=1 to np do
  9552.   if k=1 then {the |slant| parameter is a pure number}
  9553.     begin fget; sw:=fbyte; if sw>127 then sw:=sw-256;
  9554.     fget; sw:=sw*@'400+fbyte; fget; sw:=sw*@'400+fbyte;
  9555.     fget; font_info[param_base[f]].sc:=
  9556.       (sw*@'20)+(fbyte div@'20);
  9557.     end
  9558.   else store_scaled(font_info[param_base[f]+k-1].sc);
  9559. if eof(tfm_file) then abort;
  9560. for k:=np+1 to 7 do font_info[param_base[f]+k-1].sc:=0;
  9561. @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
  9562. file, and all we need to do is put the finishing touches on the data for
  9563. the new font.
  9564. @d adjust(#)==#[f]:=qo(#[f])
  9565.   {correct for the excess |min_quarterword| that was added}
  9566. @<Make final adjustments...@>=
  9567. if np>=7 then font_params[f]:=np@+else font_params[f]:=7;
  9568. hyphen_char[f]:=default_hyphen_char; skew_char[f]:=default_skew_char;
  9569. if bch_label<nl then bchar_label[f]:=bch_label+lig_kern_base[f]
  9570. else bchar_label[f]:=non_address;
  9571. font_bchar[f]:=qi(bchar);
  9572. font_false_bchar[f]:=qi(bchar);
  9573. if bchar<=ec then if bchar>=bc then
  9574.   begin qw:=char_info(f)(bchar); {N.B.: not |qi(bchar)|}
  9575.   if char_exists(qw) then font_false_bchar[f]:=non_char;
  9576.   end;
  9577. font_name[f]:=nom;
  9578. font_area[f]:=aire;
  9579. font_bc[f]:=bc; font_ec[f]:=ec; font_glue[f]:=null;
  9580. adjust(char_base); adjust(width_base); adjust(lig_kern_base);
  9581. adjust(kern_base); adjust(exten_base);
  9582. decr(param_base[f]);
  9583. fmem_ptr:=fmem_ptr+lf; font_ptr:=f; g:=f; goto done
  9584. @ Before we forget about the format of these tables, let's deal with two
  9585. of \TeX's basic scanning routines related to font information.
  9586. @<Declare procedures that scan font-related stuff@>=
  9587. procedure scan_font_ident;
  9588. var f:internal_font_number;
  9589. @!m:halfword;
  9590. begin @<Get the next non-blank non-call...@>;
  9591. if cur_cmd=def_font then f:=cur_font
  9592. else if cur_cmd=set_font then f:=cur_chr
  9593. else if cur_cmd=def_family then
  9594.   begin m:=cur_chr; scan_four_bit_int; f:=equiv(m+cur_val);
  9595.   end
  9596. else  begin print_err("Missing font identifier");
  9597. @.Missing font identifier@>
  9598.   help2("I was looking for a control sequence whose")@/
  9599.   ("current meaning has been defined by \font.");
  9600.   back_error; f:=null_font;
  9601.   end;
  9602. cur_val:=f;
  9603. @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
  9604. The boolean parameter |writing| is set |true| if the calling program
  9605. intends to change the parameter value.
  9606. @<Declare procedures that scan font-related stuff@>=
  9607. procedure find_font_dimen(@!writing:boolean);
  9608.   {sets |cur_val| to |font_info| location}
  9609. var f:internal_font_number;
  9610. @!n:integer; {the parameter number}
  9611. begin scan_int; n:=cur_val; scan_font_ident; f:=cur_val;
  9612. if n<=0 then cur_val:=fmem_ptr
  9613. else  begin if writing and(n<=space_shrink_code)and@|
  9614.     (n>=space_code)and(font_glue[f]<>null) then
  9615.     begin delete_glue_ref(font_glue[f]);
  9616.     font_glue[f]:=null;
  9617.     end;
  9618.   if n>font_params[f] then
  9619.     if f<font_ptr then cur_val:=fmem_ptr
  9620.     else @<Increase the number of parameters in the last font@>
  9621.   else cur_val:=n+param_base[f];
  9622.   end;
  9623. @<Issue an error message if |cur_val=fmem_ptr|@>;
  9624. @ @<Issue an error message if |cur_val=fmem_ptr|@>=
  9625. if cur_val=fmem_ptr then
  9626.   begin print_err("Font "); print_esc(font_id_text(f));
  9627.   print(" has only "); print_int(font_params[f]);
  9628.   print(" fontdimen parameters");
  9629. @.Font x has only...@>
  9630.   help2("To increase the number of font parameters, you must")@/
  9631.     ("use \fontdimen immediately after the \font is loaded.");
  9632.   error;
  9633.   end
  9634. @ @<Increase the number of parameters...@>=
  9635. begin repeat if fmem_ptr=font_mem_size then
  9636.   overflow("font memory",font_mem_size);
  9637. @:TeX capacity exceeded font memory}{\quad font memory@>
  9638. font_info[fmem_ptr].sc:=0; incr(fmem_ptr); incr(font_params[f]);
  9639. until n=font_params[f];
  9640. cur_val:=fmem_ptr-1; {this equals |param_base[f]+font_params[f]|}
  9641. @ When \TeX\ wants to typeset a character that doesn't exist, the
  9642. character node is not created; thus the output routine can assume
  9643. that characters exist when it sees them. The following procedure
  9644. prints a warning message unless the user has suppressed it.
  9645. @p procedure char_warning(@!f:internal_font_number;@!c:eight_bits);
  9646. begin if tracing_lost_chars>0 then
  9647.   begin begin_diagnostic;
  9648.   print_nl("Missing character: There is no ");
  9649. @.Missing character@>
  9650.   print_ASCII(c); print(" in font ");
  9651.   slow_print(font_name[f]); print_char("!"); end_diagnostic(false);
  9652.   end;
  9653. @ Here is a function that returns a pointer to a character node for a
  9654. given character in a given font. If that character doesn't exist,
  9655. |null| is returned instead.
  9656. @p function new_character(@!f:internal_font_number;@!c:eight_bits):pointer;
  9657. label exit;
  9658. var p:pointer; {newly allocated node}
  9659. begin if font_bc[f]<=c then if font_ec[f]>=c then
  9660.   if char_exists(char_info(f)(qi(c))) then
  9661.     begin p:=get_avail; font(p):=f; character(p):=qi(c);
  9662.     new_character:=p; return;
  9663.     end;
  9664. char_warning(f,c);
  9665. new_character:=null;
  9666. exit:end;
  9667. @* \[31] Device-independent file format.
  9668. The most important output produced by a run of \TeX\ is the ``device
  9669. independent'' (\.{DVI}) file that specifies where characters and rules
  9670. are to appear on printed pages. The form of these files was designed by
  9671. David R. Fuchs in 1979. Almost any reasonable typesetting device can be
  9672. @^Fuchs, David Raymond@>
  9673. @:DVI_files}{\.{DVI} files@>
  9674. driven by a program that takes \.{DVI} files as input, and dozens of such
  9675. \.{DVI}-to-whatever programs have been written. Thus, it is possible to
  9676. print the output of \TeX\ on many different kinds of equipment, using \TeX\
  9677. as a device-independent ``front end.''
  9678. A \.{DVI} file is a stream of 8-bit bytes, which may be regarded as a
  9679. series of commands in a machine-like language. The first byte of each command
  9680. is the operation code, and this code is followed by zero or more bytes
  9681. that provide parameters to the command. The parameters themselves may consist
  9682. of several consecutive bytes; for example, the `|set_rule|' command has two
  9683. parameters, each of which is four bytes long. Parameters are usually
  9684. regarded as nonnegative integers; but four-byte-long parameters,
  9685. and shorter parameters that denote distances, can be
  9686. either positive or negative. Such parameters are given in two's complement
  9687. notation. For example, a two-byte-long distance parameter has a value between
  9688. $-2^{15}$ and $2^{15}-1$. As in \.{TFM} files, numbers that occupy
  9689. more than one byte position appear in BigEndian order.
  9690. A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
  9691. or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
  9692. |pre| command, with its parameters that define the dimensions used in the
  9693. file; this must come first.  Each ``page'' consists of a |bop| command,
  9694. followed by any number of other commands that tell where characters are to
  9695. be placed on a physical page, followed by an |eop| command. The pages
  9696. appear in the order that \TeX\ generated them. If we ignore |nop| commands
  9697. and \\{fnt\_def} commands (which are allowed between any two commands in
  9698. the file), each |eop| command is immediately followed by a |bop| command,
  9699. or by a |post| command; in the latter case, there are no more pages in the
  9700. file, and the remaining bytes form the postamble.  Further details about
  9701. the postamble will be explained later.
  9702. Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
  9703. quantities that give the location number of some other byte in the file;
  9704. the first byte is number~0, then comes number~1, and so on. For example,
  9705. one of the parameters of a |bop| command points to the previous |bop|;
  9706. this makes it feasible to read the pages in backwards order, in case the
  9707. results are being directed to a device that stacks its output face up.
  9708. Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
  9709. first page occupies bytes 100 to 999, say, and if the second
  9710. page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
  9711. points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
  9712. very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
  9713. @ The \.{DVI} format is intended to be both compact and easily interpreted
  9714. by a machine. Compactness is achieved by making most of the information
  9715. implicit instead of explicit. When a \.{DVI}-reading program reads the
  9716. commands for a page, it keeps track of several quantities: (a)~The current
  9717. font |f| is an integer; this value is changed only
  9718. by \\{fnt} and \\{fnt\_num} commands. (b)~The current position on the page
  9719. is given by two numbers called the horizontal and vertical coordinates,
  9720. |h| and |v|. Both coordinates are zero at the upper left corner of the page;
  9721. moving to the right corresponds to increasing the horizontal coordinate, and
  9722. moving down corresponds to increasing the vertical coordinate. Thus, the
  9723. coordinates are essentially Cartesian, except that vertical directions are
  9724. flipped; the Cartesian version of |(h,v)| would be |(h,-v)|.  (c)~The
  9725. current spacing amounts are given by four numbers |w|, |x|, |y|, and |z|,
  9726. where |w| and~|x| are used for horizontal spacing and where |y| and~|z|
  9727. are used for vertical spacing. (d)~There is a stack containing
  9728. |(h,v,w,x,y,z)| values; the \.{DVI} commands |push| and |pop| are used to
  9729. change the current level of operation. Note that the current font~|f| is
  9730. not pushed and popped; the stack contains only information about
  9731. positioning.
  9732. The values of |h|, |v|, |w|, |x|, |y|, and |z| are signed integers having up
  9733. to 32 bits, including the sign. Since they represent physical distances,
  9734. there is a small unit of measurement such that increasing |h| by~1 means
  9735. moving a certain tiny distance to the right. The actual unit of
  9736. measurement is variable, as explained below; \TeX\ sets things up so that
  9737. its \.{DVI} output is in sp units, i.e., scaled points, in agreement with
  9738. all the |scaled| dimensions in \TeX's data structures.
  9739. @ Here is a list of all the commands that may appear in a \.{DVI} file. Each
  9740. command is specified by its symbolic name (e.g., |bop|), its opcode byte
  9741. (e.g., 139), and its parameters (if any). The parameters are followed
  9742. by a bracketed number telling how many bytes they occupy; for example,
  9743. `|p[4]|' means that parameter |p| is four bytes long.
  9744. \yskip\hang|set_char_0| 0. Typeset character number~0 from font~|f|
  9745. such that the reference point of the character is at |(h,v)|. Then
  9746. increase |h| by the width of that character. Note that a character may
  9747. have zero or negative width, so one cannot be sure that |h| will advance
  9748. after this command; but |h| usually does increase.
  9749. \yskip\hang\\{set\_char\_1} through \\{set\_char\_127} (opcodes 1 to 127).
  9750. Do the operations of |set_char_0|; but use the character whose number
  9751. matches the opcode, instead of character~0.
  9752. \yskip\hang|set1| 128 |c[1]|. Same as |set_char_0|, except that character
  9753. number~|c| is typeset. \TeX82 uses this command for characters in the
  9754. range |128<=c<256|.
  9755. \yskip\hang|@!set2| 129 |c[2]|. Same as |set1|, except that |c|~is two
  9756. bytes long, so it is in the range |0<=c<65536|. \TeX82 never uses this
  9757. command, but it should come in handy for extensions of \TeX\ that deal
  9758. with oriental languages.
  9759. @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
  9760. \yskip\hang|@!set3| 130 |c[3]|. Same as |set1|, except that |c|~is three
  9761. bytes long, so it can be as large as $2^{24}-1$. Not even the Chinese
  9762. language has this many characters, but this command might prove useful
  9763. in some yet unforeseen extension.
  9764. \yskip\hang|@!set4| 131 |c[4]|. Same as |set1|, except that |c|~is four
  9765. bytes long. Imagine that.
  9766. \yskip\hang|set_rule| 132 |a[4]| |b[4]|. Typeset a solid black rectangle
  9767. of height~|a| and width~|b|, with its bottom left corner at |(h,v)|. Then
  9768. set |h:=h+b|. If either |a<=0| or |b<=0|, nothing should be typeset. Note
  9769. that if |b<0|, the value of |h| will decrease even though nothing else happens.
  9770. See below for details about how to typeset rules so that consistency with
  9771. \MF\ is guaranteed.
  9772. \yskip\hang|@!put1| 133 |c[1]|. Typeset character number~|c| from font~|f|
  9773. such that the reference point of the character is at |(h,v)|. (The `put'
  9774. commands are exactly like the `set' commands, except that they simply put out a
  9775. character or a rule without moving the reference point afterwards.)
  9776. \yskip\hang|@!put2| 134 |c[2]|. Same as |set2|, except that |h| is not changed.
  9777. \yskip\hang|@!put3| 135 |c[3]|. Same as |set3|, except that |h| is not changed.
  9778. \yskip\hang|@!put4| 136 |c[4]|. Same as |set4|, except that |h| is not changed.
  9779. \yskip\hang|put_rule| 137 |a[4]| |b[4]|. Same as |set_rule|, except that
  9780. |h| is not changed.
  9781. \yskip\hang|nop| 138. No operation, do nothing. Any number of |nop|'s
  9782. may occur between \.{DVI} commands, but a |nop| cannot be inserted between
  9783. a command and its parameters or between two parameters.
  9784. \yskip\hang|bop| 139 $c_0[4]$ $c_1[4]$ $\ldots$ $c_9[4]$ $p[4]$. Beginning
  9785. of a page: Set |(h,v,w,x,y,z):=(0,0,0,0,0,0)| and set the stack empty. Set
  9786. the current font |f| to an undefined value.  The ten $c_i$ parameters hold
  9787. the values of \.{\\count0} $\ldots$ \.{\\count9} in \TeX\ at the time
  9788. \.{\\shipout} was invoked for this page; they can be used to identify
  9789. pages, if a user wants to print only part of a \.{DVI} file. The parameter
  9790. |p| points to the previous |bop| in the file; the first
  9791. |bop| has $p=-1$.
  9792. \yskip\hang|eop| 140.  End of page: Print what you have read since the
  9793. previous |bop|. At this point the stack should be empty. (The \.{DVI}-reading
  9794. programs that drive most output devices will have kept a buffer of the
  9795. material that appears on the page that has just ended. This material is
  9796. largely, but not entirely, in order by |v| coordinate and (for fixed |v|) by
  9797. |h|~coordinate; so it usually needs to be sorted into some order that is
  9798. appropriate for the device in question.)
  9799. \yskip\hang|push| 141. Push the current values of |(h,v,w,x,y,z)| onto the
  9800. top of the stack; do not change any of these values. Note that |f| is
  9801. not pushed.
  9802. \yskip\hang|pop| 142. Pop the top six values off of the stack and assign
  9803. them respectively to |(h,v,w,x,y,z)|. The number of pops should never
  9804. exceed the number of pushes, since it would be highly embarrassing if the
  9805. stack were empty at the time of a |pop| command.
  9806. \yskip\hang|right1| 143 |b[1]|. Set |h:=h+b|, i.e., move right |b| units.
  9807. The parameter is a signed number in two's complement notation, |-128<=b<128|;
  9808. if |b<0|, the reference point moves left.
  9809. \yskip\hang|right2| 144 |b[2]|. Same as |right1|, except that |b| is a
  9810. two-byte quantity in the range |-32768<=b<32768|.
  9811. \yskip\hang|right3| 145 |b[3]|. Same as |right1|, except that |b| is a
  9812. three-byte quantity in the range |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9813. \yskip\hang|right4| 146 |b[4]|. Same as |right1|, except that |b| is a
  9814. four-byte quantity in the range |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9815. \yskip\hang|w0| 147. Set |h:=h+w|; i.e., move right |w| units. With luck,
  9816. this parameterless command will usually suffice, because the same kind of motion
  9817. will occur several times in succession; the following commands explain how
  9818. |w| gets particular values.
  9819. \yskip\hang|w1| 148 |b[1]|. Set |w:=b| and |h:=h+b|. The value of |b| is a
  9820. signed quantity in two's complement notation, |-128<=b<128|. This command
  9821. changes the current |w|~spacing and moves right by |b|.
  9822. \yskip\hang|@!w2| 149 |b[2]|. Same as |w1|, but |b| is two bytes long,
  9823. |-32768<=b<32768|.
  9824. \yskip\hang|@!w3| 150 |b[3]|. Same as |w1|, but |b| is three bytes long,
  9825. |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9826. \yskip\hang|@!w4| 151 |b[4]|. Same as |w1|, but |b| is four bytes long,
  9827. |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9828. \yskip\hang|x0| 152. Set |h:=h+x|; i.e., move right |x| units. The `|x|'
  9829. commands are like the `|w|' commands except that they involve |x| instead
  9830. of |w|.
  9831. \yskip\hang|x1| 153 |b[1]|. Set |x:=b| and |h:=h+b|. The value of |b| is a
  9832. signed quantity in two's complement notation, |-128<=b<128|. This command
  9833. changes the current |x|~spacing and moves right by |b|.
  9834. \yskip\hang|@!x2| 154 |b[2]|. Same as |x1|, but |b| is two bytes long,
  9835. |-32768<=b<32768|.
  9836. \yskip\hang|@!x3| 155 |b[3]|. Same as |x1|, but |b| is three bytes long,
  9837. |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9838. \yskip\hang|@!x4| 156 |b[4]|. Same as |x1|, but |b| is four bytes long,
  9839. |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9840. \yskip\hang|down1| 157 |a[1]|. Set |v:=v+a|, i.e., move down |a| units.
  9841. The parameter is a signed number in two's complement notation, |-128<=a<128|;
  9842. if |a<0|, the reference point moves up.
  9843. \yskip\hang|@!down2| 158 |a[2]|. Same as |down1|, except that |a| is a
  9844. two-byte quantity in the range |-32768<=a<32768|.
  9845. \yskip\hang|@!down3| 159 |a[3]|. Same as |down1|, except that |a| is a
  9846. three-byte quantity in the range |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9847. \yskip\hang|@!down4| 160 |a[4]|. Same as |down1|, except that |a| is a
  9848. four-byte quantity in the range |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9849. \yskip\hang|y0| 161. Set |v:=v+y|; i.e., move down |y| units. With luck,
  9850. this parameterless command will usually suffice, because the same kind of motion
  9851. will occur several times in succession; the following commands explain how
  9852. |y| gets particular values.
  9853. \yskip\hang|y1| 162 |a[1]|. Set |y:=a| and |v:=v+a|. The value of |a| is a
  9854. signed quantity in two's complement notation, |-128<=a<128|. This command
  9855. changes the current |y|~spacing and moves down by |a|.
  9856. \yskip\hang|@!y2| 163 |a[2]|. Same as |y1|, but |a| is two bytes long,
  9857. |-32768<=a<32768|.
  9858. \yskip\hang|@!y3| 164 |a[3]|. Same as |y1|, but |a| is three bytes long,
  9859. |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9860. \yskip\hang|@!y4| 165 |a[4]|. Same as |y1|, but |a| is four bytes long,
  9861. |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9862. \yskip\hang|z0| 166. Set |v:=v+z|; i.e., move down |z| units. The `|z|' commands
  9863. are like the `|y|' commands except that they involve |z| instead of |y|.
  9864. \yskip\hang|z1| 167 |a[1]|. Set |z:=a| and |v:=v+a|. The value of |a| is a
  9865. signed quantity in two's complement notation, |-128<=a<128|. This command
  9866. changes the current |z|~spacing and moves down by |a|.
  9867. \yskip\hang|@!z2| 168 |a[2]|. Same as |z1|, but |a| is two bytes long,
  9868. |-32768<=a<32768|.
  9869. \yskip\hang|@!z3| 169 |a[3]|. Same as |z1|, but |a| is three bytes long,
  9870. |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9871. \yskip\hang|@!z4| 170 |a[4]|. Same as |z1|, but |a| is four bytes long,
  9872. |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9873. \yskip\hang|fnt_num_0| 171. Set |f:=0|. Font 0 must previously have been
  9874. defined by a \\{fnt\_def} instruction, as explained below.
  9875. \yskip\hang\\{fnt\_num\_1} through \\{fnt\_num\_63} (opcodes 172 to 234). Set
  9876. |f:=1|, \dots, \hbox{|f:=63|}, respectively.
  9877. \yskip\hang|fnt1| 235 |k[1]|. Set |f:=k|. \TeX82 uses this command for font
  9878. numbers in the range |64<=k<256|.
  9879. \yskip\hang|@!fnt2| 236 |k[2]|. Same as |fnt1|, except that |k|~is two
  9880. bytes long, so it is in the range |0<=k<65536|. \TeX82 never generates this
  9881. command, but large font numbers may prove useful for specifications of
  9882. color or texture, or they may be used for special fonts that have fixed
  9883. numbers in some external coding scheme.
  9884. \yskip\hang|@!fnt3| 237 |k[3]|. Same as |fnt1|, except that |k|~is three
  9885. bytes long, so it can be as large as $2^{24}-1$.
  9886. \yskip\hang|@!fnt4| 238 |k[4]|. Same as |fnt1|, except that |k|~is four
  9887. bytes long; this is for the really big font numbers (and for the negative ones).
  9888. \yskip\hang|xxx1| 239 |k[1]| |x[k]|. This command is undefined in
  9889. general; it functions as a $(k+2)$-byte |nop| unless special \.{DVI}-reading
  9890. programs are being used. \TeX82 generates |xxx1| when a short enough
  9891. \.{\\special} appears, setting |k| to the number of bytes being sent. It
  9892. is recommended that |x| be a string having the form of a keyword followed
  9893. by possible parameters relevant to that keyword.
  9894. \yskip\hang|@!xxx2| 240 |k[2]| |x[k]|. Like |xxx1|, but |0<=k<65536|.
  9895. \yskip\hang|@!xxx3| 241 |k[3]| |x[k]|. Like |xxx1|, but |0<=k<@t$2^{24}$@>|.
  9896. \yskip\hang|xxx4| 242 |k[4]| |x[k]|. Like |xxx1|, but |k| can be ridiculously
  9897. large. \TeX82 uses |xxx4| when sending a string of length 256 or more.
  9898. \yskip\hang|fnt_def1| 243 |k[1]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9899. Define font |k|, where |0<=k<256|; font definitions will be explained shortly.
  9900. \yskip\hang|@!fnt_def2| 244 |k[2]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9901. Define font |k|, where |0<=k<65536|.
  9902. \yskip\hang|@!fnt_def3| 245 |k[3]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9903. Define font |k|, where |0<=k<@t$2^{24}$@>|.
  9904. \yskip\hang|@!fnt_def4| 246 |k[4]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9905. Define font |k|, where |@t$-2^{31}$@><=k<@t$2^{31}$@>|.
  9906. \yskip\hang|pre| 247 |i[1]| |num[4]| |den[4]| |mag[4]| |k[1]| |x[k]|.
  9907. Beginning of the preamble; this must come at the very beginning of the
  9908. file. Parameters |i|, |num|, |den|, |mag|, |k|, and |x| are explained below.
  9909. \yskip\hang|post| 248. Beginning of the postamble, see below.
  9910. \yskip\hang|post_post| 249. Ending of the postamble, see below.
  9911. \yskip\noindent Commands 250--255 are undefined at the present time.
  9912. @ @d set_char_0=0 {typeset character 0 and move right}
  9913. @d set1=128 {typeset a character and move right}
  9914. @d set_rule=132 {typeset a rule and move right}
  9915. @d put_rule=137 {typeset a rule}
  9916. @d nop=138 {no operation}
  9917. @d bop=139 {beginning of page}
  9918. @d eop=140 {ending of page}
  9919. @d push=141 {save the current positions}
  9920. @d pop=142 {restore previous positions}
  9921. @d right1=143 {move right}
  9922. @d w0=147 {move right by |w|}
  9923. @d w1=148 {move right and set |w|}
  9924. @d x0=152 {move right by |x|}
  9925. @d x1=153 {move right and set |x|}
  9926. @d down1=157 {move down}
  9927. @d y0=161 {move down by |y|}
  9928. @d y1=162 {move down and set |y|}
  9929. @d z0=166 {move down by |z|}
  9930. @d z1=167 {move down and set |z|}
  9931. @d fnt_num_0=171 {set current font to 0}
  9932. @d fnt1=235 {set current font}
  9933. @d xxx1=239 {extension to \.{DVI} primitives}
  9934. @d xxx4=242 {potentially long extension to \.{DVI} primitives}
  9935. @d fnt_def1=243 {define the meaning of a font number}
  9936. @d pre=247 {preamble}
  9937. @d post=248 {postamble beginning}
  9938. @d post_post=249 {postamble ending}
  9939. @ The preamble contains basic information about the file as a whole. As
  9940. stated above, there are six parameters:
  9941. $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
  9942. The |i| byte identifies \.{DVI} format; currently this byte is always set
  9943. to~2. (The value |i=3| is currently used for an extended format that
  9944. allows a mixture of right-to-left and left-to-right typesetting.
  9945. Some day we will set |i=4|, when \.{DVI} format makes another
  9946. incompatible change---perhaps in the year 2048.)
  9947. The next two parameters, |num| and |den|, are positive integers that define
  9948. the units of measurement; they are the numerator and denominator of a
  9949. fraction by which all dimensions in the \.{DVI} file could be multiplied
  9950. in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
  9951. 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
  9952. sp in a point, \TeX\ sets
  9953. $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
  9954. @^sp@>
  9955. The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
  9956. desired magnification. The actual fraction by which dimensions are
  9957. multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
  9958. source document does not call for any `\.{true}' dimensions, and if you
  9959. change it only by specifying a different \.{\\mag} setting, the \.{DVI}
  9960. file that \TeX\ creates will be completely unchanged except for the value
  9961. of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
  9962. users to override the |mag|~setting when a \.{DVI} file is being printed.)
  9963. Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
  9964. interpreted further. The length of comment |x| is |k|, where |0<=k<256|.
  9965. @d id_byte=2 {identifies the kind of \.{DVI} files described here}
  9966. @ Font definitions for a given font number |k| contain further parameters
  9967. $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
  9968. The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
  9969. file for this font; |c| should match the check sum of the font found by
  9970. programs that read this \.{DVI} file.
  9971. @^check sum@>
  9972. Parameter |s| contains a fixed-point scale factor that is applied to
  9973. the character widths in font |k|; font dimensions in \.{TFM} files and
  9974. other font files are relative to this quantity, which is called the
  9975. ``at size'' elsewhere in this documentation. The value of |s| is
  9976. always positive and less than $2^{27}$. It is given in the same units
  9977. as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
  9978. file.  Parameter |d| is similar to |s|; it is the ``design size,'' and
  9979. (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
  9980. at $|mag|\cdot s/1000d$ times its normal size.
  9981. The remaining part of a font definition gives the external name of the font,
  9982. which is an ASCII string of length |a+l|. The number |a| is the length
  9983. of the ``area'' or directory, and |l| is the length of the font name itself;
  9984. the standard local system font area is supposed to be used when |a=0|.
  9985. The |n| field contains the area in its first |a| bytes.
  9986. Font definitions must appear before the first use of a particular font number.
  9987. Once font |k| is defined, it must not be defined again; however, we
  9988. shall see below that font definitions appear in the postamble as well as
  9989. in the pages, so in this sense each font number is defined exactly twice,
  9990. if at all. Like |nop| commands, font definitions can
  9991. appear before the first |bop|, or between an |eop| and a |bop|.
  9992. @ Sometimes it is desirable to make horizontal or vertical rules line up
  9993. precisely with certain features in characters of a font. It is possible to
  9994. guarantee the correct matching between \.{DVI} output and the characters
  9995. generated by \MF\ by adhering to the following principles: (1)~The \MF\
  9996. characters should be positioned so that a bottom edge or left edge that is
  9997. supposed to line up with the bottom or left edge of a rule appears at the
  9998. reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
  9999. ensures that the position of the rule will not be rounded differently when
  10000. the pixel size is not a perfect multiple of the units of measurement in
  10001. the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
  10002. should be equivalent to a \MF-generated character having black pixels in
  10003. precisely those raster positions whose \MF\ coordinates satisfy
  10004. |0<=x<@t$\alpha$@>b| and |0<=y<@t$\alpha$@>a|, where $\alpha$ is the number
  10005. of pixels per \.{DVI} unit.
  10006. @:METAFONT}{\MF@>
  10007. @^alignment of rules with characters@>
  10008. @^rules aligning with characters@>
  10009. @ The last page in a \.{DVI} file is followed by `|post|'; this command
  10010. introduces the postamble, which summarizes important facts that \TeX\ has
  10011. accumulated about the file, making it possible to print subsets of the data
  10012. with reasonable efficiency. The postamble has the form
  10013. $$\vbox{\halign{\hbox{#\hfil}\cr
  10014.   |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
  10015.   $\langle\,$font definitions$\,\rangle$\cr
  10016.   |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
  10017. Here |p| is a pointer to the final |bop| in the file. The next three
  10018. parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
  10019. appeared in the preamble.
  10020. Parameters |l| and |u| give respectively the height-plus-depth of the tallest
  10021. page and the width of the widest page, in the same units as other dimensions
  10022. of the file. These numbers might be used by a \.{DVI}-reading program to
  10023. position individual ``pages'' on large sheets of film or paper; however,
  10024. the standard convention for output on normal size paper is to position each
  10025. page so that the upper left-hand corner is exactly one inch from the left
  10026. and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
  10027. software that attempts cleverly to center the output; a fixed position of
  10028. the upper left corner is easiest for users to understand and to work with.
  10029. Therefore |l| and~|u| are often ignored.
  10030. Parameter |s| is the maximum stack depth (i.e., the largest excess of
  10031. |push| commands over |pop| commands) needed to process this file. Then
  10032. comes |t|, the total number of pages (|bop| commands) present.
  10033. The postamble continues with font definitions, which are any number of
  10034. \\{fnt\_def} commands as described above, possibly interspersed with |nop|
  10035. commands. Each font number that is used in the \.{DVI} file must be defined
  10036. exactly twice: Once before it is first selected by a \\{fnt} command, and once
  10037. in the postamble.
  10038. @ The last part of the postamble, following the |post_post| byte that
  10039. signifies the end of the font definitions, contains |q|, a pointer to the
  10040. |post| command that started the postamble.  An identification byte, |i|,
  10041. comes next; this currently equals~2, as in the preamble.
  10042. The |i| byte is followed by four or more bytes that are all equal to
  10043. the decimal number 223 (i.e., @'337 in octal). \TeX\ puts out four to seven of
  10044. these trailing bytes, until the total length of the file is a multiple of
  10045. four bytes, since this works out best on machines that pack four bytes per
  10046. word; but any number of 223's is allowed, as long as there are at least four
  10047. of them. In effect, 223 is a sort of signature that is added at the very end.
  10048. @^Fuchs, David Raymond@>
  10049. This curious way to finish off a \.{DVI} file makes it feasible for
  10050. \.{DVI}-reading programs to find the postamble first, on most computers,
  10051. even though \TeX\ wants to write the postamble last. Most operating
  10052. systems permit random access to individual words or bytes of a file, so
  10053. the \.{DVI} reader can start at the end and skip backwards over the 223's
  10054. until finding the identification byte. Then it can back up four bytes, read
  10055. |q|, and move to byte |q| of the file. This byte should, of course,
  10056. contain the value 248 (|post|); now the postamble can be read, so the
  10057. \.{DVI} reader can discover all the information needed for typesetting the
  10058. pages. Note that it is also possible to skip through the \.{DVI} file at
  10059. reasonably high speed to locate a particular page, if that proves
  10060. desirable. This saves a lot of time, since \.{DVI} files used in production
  10061. jobs tend to be large.
  10062. Unfortunately, however, standard \PASCAL\ does not include the ability to
  10063. @^system dependencies@>
  10064. access a random position in a file, or even to determine the length of a file.
  10065. Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
  10066. format has been designed to work most efficiently with modern operating systems.
  10067. But if \.{DVI} files have to be processed under the restrictions of standard
  10068. \PASCAL, one can simply read them from front to back, since the necessary
  10069. header information is present in the preamble and in the font definitions.
  10070. (The |l| and |u| and |s| and |t| parameters, which appear only in the
  10071. postamble, are ``frills'' that are handy but not absolutely necessary.)
  10072. @* \[32] Shipping pages out.
  10073. After considering \TeX's eyes and stomach, we come now to the bowels.
  10074. @^bowels@>
  10075. The |ship_out| procedure is given a pointer to a box; its mission is
  10076. to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
  10077. The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
  10078. corner of the box being shipped.
  10079. Since boxes can be inside of boxes inside of boxes, the main work of
  10080. |ship_out| is done by two mutually recursive routines, |hlist_out|
  10081. and |vlist_out|, which traverse the hlists and vlists inside of horizontal
  10082. and vertical boxes.
  10083. As individual pages are being processed, we need to accumulate
  10084. information about the entire set of pages, since such statistics must be
  10085. reported in the postamble. The global variables |total_pages|, |max_v|,
  10086. |max_h|, |max_push|, and |last_bop| are used to record this information.
  10087. The variable |doing_leaders| is |true| while leaders are being output.
  10088. The variable |dead_cycles| contains the number of times an output routine
  10089. has been initiated since the last |ship_out|.
  10090. A few additional global variables are also defined here for use in
  10091. |vlist_out| and |hlist_out|. They could have been local variables, but
  10092. that would waste stack space when boxes are deeply nested, since the
  10093. values of these variables are not needed during recursive calls.
  10094. @^recursion@>
  10095. @<Glob...@>=
  10096. @!total_pages:integer; {the number of pages that have been shipped out}
  10097. @!max_v:scaled; {maximum height-plus-depth of pages shipped so far}
  10098. @!max_h:scaled; {maximum width of pages shipped so far}
  10099. @!max_push:integer; {deepest nesting of |push| commands encountered so far}
  10100. @!last_bop:integer; {location of previous |bop| in the \.{DVI} output}
  10101. @!dead_cycles:integer; {recent outputs that didn't ship anything out}
  10102. @!doing_leaders:boolean; {are we inside a leader box?}
  10103. @!c,@!f:quarterword; {character and font in current |char_node|}
  10104. @!rule_ht,@!rule_dp,@!rule_wd:scaled; {size of current rule being output}
  10105. @!g:pointer; {current glue specification}
  10106. @!lq,@!lr:integer; {quantities used in calculations for leaders}
  10107. @ @<Set init...@>=
  10108. total_pages:=0; max_v:=0; max_h:=0; max_push:=0; last_bop:=-1;
  10109. doing_leaders:=false; dead_cycles:=0; cur_s:=-1;
  10110. @ The \.{DVI} bytes are output to a buffer instead of being written directly
  10111. to the output file. This makes it possible to reduce the overhead of
  10112. subroutine calls, thereby measurably speeding up the computation, since
  10113. output of \.{DVI} bytes is part of \TeX's inner loop. And it has another
  10114. advantage as well, since we can change instructions in the buffer in order to
  10115. make the output more compact. For example, a `|down2|' command can be
  10116. changed to a `|y2|', thereby making a subsequent `|y0|' command possible,
  10117. saving two bytes.
  10118. The output buffer is divided into two parts of equal size; the bytes found
  10119. in |dvi_buf[0..half_buf-1]| constitute the first half, and those in
  10120. |dvi_buf[half_buf..dvi_buf_size-1]| constitute the second. The global
  10121. variable |dvi_ptr| points to the position that will receive the next
  10122. output byte. When |dvi_ptr| reaches |dvi_limit|, which is always equal
  10123. to one of the two values |half_buf| or |dvi_buf_size|, the half buffer that
  10124. is about to be invaded next is sent to the output and |dvi_limit| is
  10125. changed to its other value. Thus, there is always at least a half buffer's
  10126. worth of information present, except at the very beginning of the job.
  10127. Bytes of the \.{DVI} file are numbered sequentially starting with 0;
  10128. the next byte to be generated will be number |dvi_offset+dvi_ptr|.
  10129. A byte is present in the buffer only if its number is |>=dvi_gone|.
  10130. @<Types...@>=
  10131. @!dvi_index=0..dvi_buf_size; {an index into the output buffer}
  10132. @ Some systems may find it more efficient to make |dvi_buf| a |packed|
  10133. array, since output of four bytes at once may be facilitated.
  10134. @^system dependencies@>
  10135. @<Glob...@>=
  10136. @!dvi_buf:array[dvi_index] of eight_bits; {buffer for \.{DVI} output}
  10137. @!half_buf:dvi_index; {half of |dvi_buf_size|}
  10138. @!dvi_limit:dvi_index; {end of the current half buffer}
  10139. @!dvi_ptr:dvi_index; {the next available buffer address}
  10140. @!dvi_offset:integer; {|dvi_buf_size| times the number of times the
  10141.   output buffer has been fully emptied}
  10142. @!dvi_gone:integer; {the number of bytes already output to |dvi_file|}
  10143. @ Initially the buffer is all in one piece; we will output half of it only
  10144. after it first fills up.
  10145. @<Set init...@>=
  10146. half_buf:=dvi_buf_size div 2; dvi_limit:=dvi_buf_size; dvi_ptr:=0;
  10147. dvi_offset:=0; dvi_gone:=0;
  10148. @ The actual output of |dvi_buf[a..b]| to |dvi_file| is performed by calling
  10149. |write_dvi(a,b)|. For best results, this procedure should be optimized to
  10150. run as fast as possible on each particular system, since it is part of
  10151. \TeX's inner loop. It is safe to assume that |a| and |b+1| will both be
  10152. multiples of 4 when |write_dvi(a,b)| is called; therefore it is possible on
  10153. many machines to use efficient methods to pack four bytes per word and to
  10154. output an array of words with one system call.
  10155. @^system dependencies@>
  10156. @^inner loop@>
  10157. @^defecation@>
  10158. @p procedure write_dvi(@!a,@!b:dvi_index);
  10159. var k:dvi_index;
  10160. begin for k:=a to b do write(dvi_file,dvi_buf[k]);
  10161. @ To put a byte in the buffer without paying the cost of invoking a procedure
  10162. each time, we use the macro |dvi_out|.
  10163. @d dvi_out(#)==@+begin dvi_buf[dvi_ptr]:=#; incr(dvi_ptr);
  10164.   if dvi_ptr=dvi_limit then dvi_swap;
  10165.   end
  10166. @p procedure dvi_swap; {outputs half of the buffer}
  10167. begin if dvi_limit=dvi_buf_size then
  10168.   begin write_dvi(0,half_buf-1); dvi_limit:=half_buf;
  10169.   dvi_offset:=dvi_offset+dvi_buf_size; dvi_ptr:=0;
  10170.   end
  10171. else  begin write_dvi(half_buf,dvi_buf_size-1); dvi_limit:=dvi_buf_size;
  10172.   end;
  10173. dvi_gone:=dvi_gone+half_buf;
  10174. @ Here is how we clean out the buffer when \TeX\ is all through; |dvi_ptr|
  10175. will be a multiple of~4.
  10176. @<Empty the last bytes out of |dvi_buf|@>=
  10177. if dvi_limit=half_buf then write_dvi(half_buf,dvi_buf_size-1);
  10178. if dvi_ptr>0 then write_dvi(0,dvi_ptr-1)
  10179. @ The |dvi_four| procedure outputs four bytes in two's complement notation,
  10180. without risking arithmetic overflow.
  10181. @p procedure dvi_four(@!x:integer);
  10182. begin if x>=0 then dvi_out(x div @'100000000)
  10183. else  begin x:=x+@'10000000000;
  10184.   x:=x+@'10000000000;
  10185.   dvi_out((x div @'100000000) + 128);
  10186.   end;
  10187. x:=x mod @'100000000; dvi_out(x div @'200000);
  10188. x:=x mod @'200000; dvi_out(x div @'400);
  10189. dvi_out(x mod @'400);
  10190. @ A mild optimization of the output is performed by the |dvi_pop|
  10191. routine, which issues a |pop| unless it is possible to cancel a
  10192. `|push| |pop|' pair. The parameter to |dvi_pop| is the byte address
  10193. following the old |push| that matches the new |pop|.
  10194. @p procedure dvi_pop(@!l:integer);
  10195. begin if (l=dvi_offset+dvi_ptr)and(dvi_ptr>0) then decr(dvi_ptr)
  10196. else dvi_out(pop);
  10197. @ Here's a procedure that outputs a font definition. Since \TeX82 uses at
  10198. most 256 different fonts per job, |fnt_def1| is always used as the command code.
  10199. @p procedure dvi_font_def(@!f:internal_font_number);
  10200. var k:pool_pointer; {index into |str_pool|}
  10201. begin dvi_out(fnt_def1);
  10202. dvi_out(f-font_base-1);@/
  10203. dvi_out(qo(font_check[f].b0));
  10204. dvi_out(qo(font_check[f].b1));
  10205. dvi_out(qo(font_check[f].b2));
  10206. dvi_out(qo(font_check[f].b3));@/
  10207. dvi_four(font_size[f]);
  10208. dvi_four(font_dsize[f]);@/
  10209. dvi_out(length(font_area[f]));
  10210. dvi_out(length(font_name[f]));
  10211. @<Output the font name whose internal number is |f|@>;
  10212. @ @<Output the font name whose internal number is |f|@>=
  10213. for k:=str_start[font_area[f]] to str_start[font_area[f]+1]-1 do
  10214.   dvi_out(so(str_pool[k]));
  10215. for k:=str_start[font_name[f]] to str_start[font_name[f]+1]-1 do
  10216.   dvi_out(so(str_pool[k]))
  10217. @ Versions of \TeX\ intended for small computers might well choose to omit
  10218. the ideas in the next few parts of this program, since it is not really
  10219. necessary to optimize the \.{DVI} code by making use of the |w0|, |x0|,
  10220. |y0|, and |z0| commands. Furthermore, the algorithm that we are about to
  10221. describe does not pretend to give an optimum reduction in the length
  10222. of the \.{DVI} code; after all, speed is more important than compactness.
  10223. But the method is surprisingly effective, and it takes comparatively little
  10224. time.
  10225. We can best understand the basic idea by first considering a simpler problem
  10226. that has the same essential characteristics. Given a sequence of digits,
  10227. say $3\,1\,4\,1\,5\,9\,2\,6\,5\,3\,5\,8\,9$, we want to assign subscripts
  10228. $d$, $y$, or $z$ to each digit so as to maximize the number of ``$y$-hits''
  10229. and ``$z$-hits''; a $y$-hit is an instance of two appearances of the same
  10230. digit with the subscript $y$, where no $y$'s intervene between the two
  10231. appearances, and a $z$-hit is defined similarly. For example, the sequence
  10232. above could be decorated with subscripts as follows:
  10233. $$3_z\,1_y\,4_d\,1_y\,5_y\,9_d\,2_d\,6_d\,5_y\,3_z\,5_y\,8_d\,9_d.$$
  10234. There are three $y$-hits ($1_y\ldots1_y$ and $5_y\ldots5_y\ldots5_y$) and
  10235. one $z$-hit ($3_z\ldots3_z$); there are no $d$-hits, since the two appearances
  10236. of $9_d$ have $d$'s between them, but we don't count $d$-hits so it doesn't
  10237. matter how many there are. These subscripts are analogous to the \.{DVI}
  10238. commands called \\{down}, $y$, and $z$, and the digits are analogous to
  10239. different amounts of vertical motion; a $y$-hit or $z$-hit corresponds to
  10240. the opportunity to use the one-byte commands |y0| or |z0| in a \.{DVI} file.
  10241. \TeX's method of assigning subscripts works like this: Append a new digit,
  10242. say $\delta$, to the right of the sequence. Now look back through the
  10243. sequence until one of the following things happens: (a)~You see
  10244. $\delta_y$ or $\delta_z$, and this was the first time you encountered a
  10245. $y$ or $z$ subscript, respectively.  Then assign $y$ or $z$ to the new
  10246. $\delta$; you have scored a hit. (b)~You see $\delta_d$, and no $y$
  10247. subscripts have been encountered so far during this search.  Then change
  10248. the previous $\delta_d$ to $\delta_y$ (this corresponds to changing a
  10249. command in the output buffer), and assign $y$ to the new $\delta$; it's
  10250. another hit.  (c)~You see $\delta_d$, and a $y$ subscript has been seen
  10251. but not a $z$.  Change the previous $\delta_d$ to $\delta_z$ and assign
  10252. $z$ to the new $\delta$. (d)~You encounter both $y$ and $z$ subscripts
  10253. before encountering a suitable $\delta$, or you scan all the way to the
  10254. front of the sequence. Assign $d$ to the new $\delta$; this assignment may
  10255. be changed later.
  10256. The subscripts $3_z\,1_y\,4_d\ldots\,$ in the example above were, in fact,
  10257. produced by this procedure, as the reader can verify. (Go ahead and try it.)
  10258. @ In order to implement such an idea, \TeX\ maintains a stack of pointers
  10259. to the \\{down}, $y$, and $z$ commands that have been generated for the
  10260. current page. And there is a similar stack for \\{right}, |w|, and |x|
  10261. commands. These stacks are called the down stack and right stack, and their
  10262. top elements are maintained in the variables |down_ptr| and |right_ptr|.
  10263. Each entry in these stacks contains four fields: The |width| field is
  10264. the amount of motion down or to the right; the |location| field is the
  10265. byte number of the \.{DVI} command in question (including the appropriate
  10266. |dvi_offset|); the |link| field points to the next item below this one
  10267. on the stack; and the |info| field encodes the options for possible change
  10268. in the \.{DVI} command.
  10269. @d movement_node_size=3 {number of words per entry in the down and right stacks}
  10270. @d location(#)==mem[#+2].int {\.{DVI} byte number for a movement command}
  10271. @<Glob...@>=
  10272. @!down_ptr,@!right_ptr:pointer; {heads of the down and right stacks}
  10273. @ @<Set init...@>=
  10274. down_ptr:=null; right_ptr:=null;
  10275. @ Here is a subroutine that produces a \.{DVI} command for some specified
  10276. downward or rightward motion. It has two parameters: |w| is the amount
  10277. of motion, and |o| is either |down1| or |right1|. We use the fact that
  10278. the command codes have convenient arithmetic properties: |y1-down1=w1-right1|
  10279. and |z1-down1=x1-right1|.
  10280. @p procedure movement(@!w:scaled;@!o:eight_bits);
  10281. label exit,found,not_found,2,1;
  10282. var mstate:small_number; {have we seen a |y| or |z|?}
  10283. @!p,@!q:pointer; {current and top nodes on the stack}
  10284. @!k:integer; {index into |dvi_buf|, modulo |dvi_buf_size|}
  10285. begin q:=get_node(movement_node_size); {new node for the top of the stack}
  10286. width(q):=w; location(q):=dvi_offset+dvi_ptr;
  10287. if o=down1 then
  10288.   begin link(q):=down_ptr; down_ptr:=q;
  10289.   end
  10290. else  begin link(q):=right_ptr; right_ptr:=q;
  10291.   end;
  10292. @<Look at the other stack entries until deciding what sort of \.{DVI} command
  10293.   to generate; |goto found| if node |p| is a ``hit''@>;
  10294. @<Generate a |down| or |right| command for |w| and |return|@>;
  10295. found: @<Generate a |y0| or |z0| command in order to reuse a previous
  10296.   appearance of~|w|@>;
  10297. exit:end;
  10298. @ The |info| fields in the entries of the down stack or the right stack
  10299. have six possible settings: |y_here| or |z_here| mean that the \.{DVI}
  10300. command refers to |y| or |z|, respectively (or to |w| or |x|, in the
  10301. case of horizontal motion); |yz_OK| means that the \.{DVI} command is
  10302. \\{down} (or \\{right}) but can be changed to either |y| or |z| (or
  10303. to either |w| or |x|); |y_OK| means that it is \\{down} and can be changed
  10304. to |y| but not |z|; |z_OK| is similar; and |d_fixed| means it must stay
  10305. \\{down}.
  10306. The four settings |yz_OK|, |y_OK|, |z_OK|, |d_fixed| would not need to
  10307. be distinguished from each other if we were simply solving the
  10308. digit-subscripting problem mentioned above. But in \TeX's case there is
  10309. a complication because of the nested structure of |push| and |pop|
  10310. commands. Suppose we add parentheses to the digit-subscripting problem,
  10311. redefining hits so that $\delta_y\ldots \delta_y$ is a hit if all $y$'s between
  10312. the $\delta$'s are enclosed in properly nested parentheses, and if the
  10313. parenthesis level of the right-hand $\delta_y$ is deeper than or equal to
  10314. that of the left-hand one. Thus, `(' and `)' correspond to `|push|'
  10315. and `|pop|'. Now if we want to assign a subscript to the final 1 in the
  10316. sequence
  10317. $$2_y\,7_d\,1_d\,(\,8_z\,2_y\,8_z\,)\,1$$
  10318. we cannot change the previous $1_d$ to $1_y$, since that would invalidate
  10319. the $2_y\ldots2_y$ hit. But we can change it to $1_z$, scoring a hit
  10320. since the intervening $8_z$'s are enclosed in parentheses.
  10321. The program below removes movement nodes that are introduced after a |push|,
  10322. before it outputs the corresponding |pop|.
  10323. @d y_here=1 {|info| when the movement entry points to a |y| command}
  10324. @d z_here=2 {|info| when the movement entry points to a |z| command}
  10325. @d yz_OK=3 {|info| corresponding to an unconstrained \\{down} command}
  10326. @d y_OK=4 {|info| corresponding to a \\{down} that can't become a |z|}
  10327. @d z_OK=5 {|info| corresponding to a \\{down} that can't become a |y|}
  10328. @d d_fixed=6 {|info| corresponding to a \\{down} that can't change}
  10329. @ When the |movement| procedure gets to the label |found|, the value of
  10330. |info(p)| will be either |y_here| or |z_here|. If it is, say, |y_here|,
  10331. the procedure generates a |y0| command (or a |w0| command), and marks
  10332. all |info| fields between |q| and |p| so that |y| is not OK in that range.
  10333. @<Generate a |y0| or |z0| command...@>=
  10334. info(q):=info(p);
  10335. if info(q)=y_here then
  10336.   begin dvi_out(o+y0-down1); {|y0| or |w0|}
  10337.   while link(q)<>p do
  10338.     begin q:=link(q);
  10339.     case info(q) of
  10340.     yz_OK: info(q):=z_OK;
  10341.     y_OK: info(q):=d_fixed;
  10342.     othercases do_nothing
  10343.     endcases;
  10344.     end;
  10345.   end
  10346. else  begin dvi_out(o+z0-down1); {|z0| or |x0|}
  10347.   while link(q)<>p do
  10348.     begin q:=link(q);
  10349.     case info(q) of
  10350.     yz_OK: info(q):=y_OK;
  10351.     z_OK: info(q):=d_fixed;
  10352.     othercases do_nothing
  10353.     endcases;
  10354.     end;
  10355.   end
  10356. @ @<Generate a |down| or |right|...@>=
  10357. info(q):=yz_OK;
  10358. if abs(w)>=@'40000000 then
  10359.   begin dvi_out(o+3); {|down4| or |right4|}
  10360.   dvi_four(w); return;
  10361.   end;
  10362. if abs(w)>=@'100000 then
  10363.   begin dvi_out(o+2); {|down3| or |right3|}
  10364.   if w<0 then w:=w+@'100000000;
  10365.   dvi_out(w div @'200000); w:=w mod @'200000; goto 2;
  10366.   end;
  10367. if abs(w)>=@'200 then
  10368.   begin dvi_out(o+1); {|down2| or |right2|}
  10369.   if w<0 then w:=w+@'200000;
  10370.   goto 2;
  10371.   end;
  10372. dvi_out(o); {|down1| or |right1|}
  10373. if w<0 then w:=w+@'400;
  10374. goto 1;
  10375. 2: dvi_out(w div @'400);
  10376. 1: dvi_out(w mod @'400); return
  10377. @ As we search through the stack, we are in one of three states,
  10378. |y_seen|, |z_seen|, or |none_seen|, depending on whether we have
  10379. encountered |y_here| or |z_here| nodes. These states are encoded as
  10380. multiples of 6, so that they can be added to the |info| fields for quick
  10381. decision-making.
  10382. @^inner loop@>
  10383. @d none_seen=0 {no |y_here| or |z_here| nodes have been encountered yet}
  10384. @d y_seen=6 {we have seen |y_here| but not |z_here|}
  10385. @d z_seen=12 {we have seen |z_here| but not |y_here|}
  10386. @<Look at the other stack entries until deciding...@>=
  10387. p:=link(q); mstate:=none_seen;
  10388. while p<>null do
  10389.   begin if width(p)=w then @<Consider a node with matching width;
  10390.     |goto found| if it's a hit@>
  10391.   else  case mstate+info(p) of
  10392.     none_seen+y_here: mstate:=y_seen;
  10393.     none_seen+z_here: mstate:=z_seen;
  10394.     y_seen+z_here,z_seen+y_here: goto not_found;
  10395.     othercases do_nothing
  10396.     endcases;
  10397.   p:=link(p);
  10398.   end;
  10399. not_found:
  10400. @ We might find a valid hit in a |y| or |z| byte that is already gone
  10401. from the buffer. But we can't change bytes that are gone forever; ``the
  10402. moving finger writes, $\ldots\,\,$.''
  10403. @<Consider a node with matching width...@>=
  10404. case mstate+info(p) of
  10405. none_seen+yz_OK,none_seen+y_OK,z_seen+yz_OK,z_seen+y_OK:@t@>@;@/
  10406.   if location(p)<dvi_gone then goto not_found
  10407.   else @<Change buffered instruction to |y| or |w| and |goto found|@>;
  10408. none_seen+z_OK,y_seen+yz_OK,y_seen+z_OK:@t@>@;@/
  10409.   if location(p)<dvi_gone then goto not_found
  10410.   else @<Change buffered instruction to |z| or |x| and |goto found|@>;
  10411. none_seen+y_here,none_seen+z_here,y_seen+z_here,z_seen+y_here: goto found;
  10412. othercases do_nothing
  10413. endcases
  10414. @ @<Change buffered instruction to |y| or |w| and |goto found|@>=
  10415. begin k:=location(p)-dvi_offset;
  10416. if k<0 then k:=k+dvi_buf_size;
  10417. dvi_buf[k]:=dvi_buf[k]+y1-down1;
  10418. info(p):=y_here; goto found;
  10419. @ @<Change buffered instruction to |z| or |x| and |goto found|@>=
  10420. begin k:=location(p)-dvi_offset;
  10421. if k<0 then k:=k+dvi_buf_size;
  10422. dvi_buf[k]:=dvi_buf[k]+z1-down1;
  10423. info(p):=z_here; goto found;
  10424. @ In case you are wondering when all the movement nodes are removed from
  10425. \TeX's memory, the answer is that they are recycled just before
  10426. |hlist_out| and |vlist_out| finish outputting a box. This restores the
  10427. down and right stacks to the state they were in before the box was output,
  10428. except that some |info|'s may have become more restrictive.
  10429. @p procedure prune_movements(@!l:integer);
  10430.   {delete movement nodes with |location>=l|}
  10431. label done,exit;
  10432. var p:pointer; {node being deleted}
  10433. begin while down_ptr<>null do
  10434.   begin if location(down_ptr)<l then goto done;
  10435.   p:=down_ptr; down_ptr:=link(p); free_node(p,movement_node_size);
  10436.   end;
  10437. done: while right_ptr<>null do
  10438.   begin if location(right_ptr)<l then return;
  10439.   p:=right_ptr; right_ptr:=link(p); free_node(p,movement_node_size);
  10440.   end;
  10441. exit:end;
  10442. @ The actual distances by which we want to move might be computed as the
  10443. sum of several separate movements. For example, there might be several
  10444. glue nodes in succession, or we might want to move right by the width of
  10445. some box plus some amount of glue. More importantly, the baselineskip
  10446. distances are computed in terms of glue together with the depth and
  10447. height of adjacent boxes, and we want the \.{DVI} file to lump these
  10448. three quantities together into a single motion.
  10449. Therefore, \TeX\ maintains two pairs of global variables: |dvi_h| and |dvi_v|
  10450. are the |h| and |v| coordinates corresponding to the commands actually
  10451. output to the \.{DVI} file, while |cur_h| and |cur_v| are the coordinates
  10452. corresponding to the current state of the output routines. Coordinate
  10453. changes will accumulate in |cur_h| and |cur_v| without being reflected
  10454. in the output, until such a change becomes necessary or desirable; we
  10455. can call the |movement| procedure whenever we want to make |dvi_h=cur_h|
  10456. or |dvi_v=cur_v|.
  10457. The current font reflected in the \.{DVI} output is called |dvi_f|;
  10458. there is no need for a `\\{cur\_f}' variable.
  10459. The depth of nesting of |hlist_out| and |vlist_out| is called |cur_s|;
  10460. this is essentially the depth of |push| commands in the \.{DVI} output.
  10461. @d synch_h==if cur_h<>dvi_h then
  10462.     begin movement(cur_h-dvi_h,right1); dvi_h:=cur_h;
  10463.     end
  10464. @d synch_v==if cur_v<>dvi_v then
  10465.     begin movement(cur_v-dvi_v,down1); dvi_v:=cur_v;
  10466.     end
  10467. @<Glob...@>=
  10468. @!dvi_h,@!dvi_v:scaled; {a \.{DVI} reader program thinks we are here}
  10469. @!cur_h,@!cur_v:scaled; {\TeX\ thinks we are here}
  10470. @!dvi_f:internal_font_number; {the current font}
  10471. @!cur_s:integer; {current depth of output box nesting, initially $-1$}
  10472. @ @<Initialize variables as |ship_out| begins@>=
  10473. dvi_h:=0; dvi_v:=0; cur_h:=h_offset; dvi_f:=null_font;
  10474. ensure_dvi_open;
  10475. if total_pages=0 then
  10476.   begin dvi_out(pre); dvi_out(id_byte); {output the preamble}
  10477. @^preamble of \.{DVI} file@>
  10478.   dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
  10479.   prepare_mag; dvi_four(mag); {magnification factor is frozen}
  10480.   old_setting:=selector; selector:=new_string;
  10481.   print(" TeX output "); print_int(year); print_char(".");
  10482.   print_two(month); print_char("."); print_two(day);
  10483.   print_char(":"); print_two(time div 60);
  10484.   print_two(time mod 60);
  10485.   selector:=old_setting; dvi_out(cur_length);
  10486.   for s:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[s]));
  10487.   pool_ptr:=str_start[str_ptr]; {flush the current string}
  10488.   end
  10489. @ When |hlist_out| is called, its duty is to output the box represented
  10490. by the |hlist_node| pointed to by |temp_ptr|. The reference point of that
  10491. box has coordinates |(cur_h,cur_v)|.
  10492. Similarly, when |vlist_out| is called, its duty is to output the box represented
  10493. by the |vlist_node| pointed to by |temp_ptr|. The reference point of that
  10494. box has coordinates |(cur_h,cur_v)|.
  10495. @^recursion@>
  10496. @p procedure@?vlist_out; forward; {|hlist_out| and |vlist_out| are mutually
  10497.   recursive}
  10498. @ The recursive procedures |hlist_out| and |vlist_out| each have local variables
  10499. |save_h| and |save_v| to hold the values of |dvi_h| and |dvi_v| just before
  10500. entering a new level of recursion.  In effect, the values of |save_h| and
  10501. |save_v| on \TeX's run-time stack correspond to the values of |h| and |v|
  10502. that a \.{DVI}-reading program will push onto its coordinate stack.
  10503. @d move_past=13 {go to this label when advancing past glue or a rule}
  10504. @d fin_rule=14 {go to this label to finish processing a rule}
  10505. @d next_p=15 {go to this label when finished with node |p|}
  10506. @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
  10507. procedure hlist_out; {output an |hlist_node| box}
  10508. label reswitch, move_past, fin_rule, next_p;
  10509. var base_line: scaled; {the baseline coordinate for this box}
  10510. @!left_edge: scaled; {the left coordinate for this box}
  10511. @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
  10512. @!this_box: pointer; {pointer to containing box}
  10513. @!g_order: glue_ord; {applicable order of infinity for glue}
  10514. @!g_sign: normal..shrinking; {selects type of glue}
  10515. @!p:pointer; {current position in the hlist}
  10516. @!save_loc:integer; {\.{DVI} byte location upon entry}
  10517. @!leader_box:pointer; {the leader box being replicated}
  10518. @!leader_wd:scaled; {width of leader box being replicated}
  10519. @!lx:scaled; {extra space between leader boxes}
  10520. @!outer_doing_leaders:boolean; {were we doing leaders?}
  10521. @!edge:scaled; {left edge of sub-box, or right edge of leader space}
  10522. @!glue_temp:real; {glue value before rounding}
  10523. begin this_box:=temp_ptr; g_order:=glue_order(this_box);
  10524. g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
  10525. incr(cur_s);
  10526. if cur_s>0 then dvi_out(push);
  10527. if cur_s>max_push then max_push:=cur_s;
  10528. save_loc:=dvi_offset+dvi_ptr; base_line:=cur_v; left_edge:=cur_h;
  10529. while p<>null do @<Output node |p| for |hlist_out| and move to the next node,
  10530.   maintaining the condition |cur_v=base_line|@>;
  10531. prune_movements(save_loc);
  10532. if cur_s>0 then dvi_pop(save_loc);
  10533. decr(cur_s);
  10534. @ We ought to give special care to the efficiency of one part of |hlist_out|,
  10535. since it belongs to \TeX's inner loop. When a |char_node| is encountered,
  10536. we save a little time by processing several nodes in succession until
  10537. reaching a non-|char_node|. The program uses the fact that |set_char_0=0|.
  10538. @^inner loop@>
  10539. @<Output node |p| for |hlist_out|...@>=
  10540. reswitch: if is_char_node(p) then
  10541.   begin synch_h; synch_v;
  10542.   repeat f:=font(p); c:=character(p);
  10543.   if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
  10544.   if c>=qi(128) then dvi_out(set1);
  10545.   dvi_out(qo(c));@/
  10546.   cur_h:=cur_h+char_width(f)(char_info(f)(c));
  10547.   p:=link(p);
  10548.   until not is_char_node(p);
  10549.   dvi_h:=cur_h;
  10550.   end
  10551. else @<Output the non-|char_node| |p| for |hlist_out|
  10552.     and move to the next node@>
  10553. @ @<Change font |dvi_f| to |f|@>=
  10554. begin if not font_used[f] then
  10555.   begin dvi_font_def(f); font_used[f]:=true;
  10556.   end;
  10557. if f<=64+font_base then dvi_out(f-font_base-1+fnt_num_0)
  10558. else  begin dvi_out(fnt1); dvi_out(f-font_base-1);
  10559.   end;
  10560. dvi_f:=f;
  10561. @ @<Output the non-|char_node| |p| for |hlist_out|...@>=
  10562. begin case type(p) of
  10563. hlist_node,vlist_node:@<Output a box in an hlist@>;
  10564. rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
  10565.   goto fin_rule;
  10566.   end;
  10567. whatsit_node: @<Output the whatsit node |p| in an hlist@>;
  10568. glue_node: @<Move right or output leaders@>;
  10569. kern_node,math_node:cur_h:=cur_h+width(p);
  10570. ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>;
  10571. othercases do_nothing
  10572. endcases;@/
  10573. goto next_p;
  10574. fin_rule: @<Output a rule in an hlist@>;
  10575. move_past: cur_h:=cur_h+rule_wd;
  10576. next_p:p:=link(p);
  10577. @ @<Output a box in an hlist@>=
  10578. if list_ptr(p)=null then cur_h:=cur_h+width(p)
  10579. else  begin save_h:=dvi_h; save_v:=dvi_v;
  10580.   cur_v:=base_line+shift_amount(p); {shift the box down}
  10581.   temp_ptr:=p; edge:=cur_h;
  10582.   if type(p)=vlist_node then vlist_out@+else hlist_out;
  10583.   dvi_h:=save_h; dvi_v:=save_v;
  10584.   cur_h:=edge+width(p); cur_v:=base_line;
  10585.   end
  10586. @ @<Output a rule in an hlist@>=
  10587. if is_running(rule_ht) then rule_ht:=height(this_box);
  10588. if is_running(rule_dp) then rule_dp:=depth(this_box);
  10589. rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
  10590. if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
  10591.   begin synch_h; cur_v:=base_line+rule_dp; synch_v;
  10592.   dvi_out(set_rule); dvi_four(rule_ht); dvi_four(rule_wd);
  10593.   cur_v:=base_line; dvi_h:=dvi_h+rule_wd;
  10594.   end
  10595. @ @d vet_glue(#)== glue_temp:=#;
  10596.   if glue_temp>float_constant(1000000000) then
  10597.            glue_temp:=float_constant(1000000000)
  10598.   else if glue_temp<-float_constant(1000000000) then
  10599.            glue_temp:=-float_constant(1000000000)
  10600. @<Move right or output leaders@>=
  10601. begin g:=glue_ptr(p); rule_wd:=width(g);
  10602. if g_sign<>normal then
  10603.   begin if g_sign=stretching then
  10604.     begin if stretch_order(g)=g_order then
  10605.       begin vet_glue(float(glue_set(this_box))*stretch(g));
  10606. @^real multiplication@>
  10607.       rule_wd:=rule_wd+round(glue_temp);
  10608.       end;
  10609.     end
  10610.   else if shrink_order(g)=g_order then
  10611.     begin vet_glue(float(glue_set(this_box))*shrink(g));
  10612.       rule_wd:=rule_wd-round(glue_temp);
  10613.     end;
  10614.   end;
  10615. if subtype(p)>=a_leaders then
  10616.   @<Output leaders in an hlist, |goto fin_rule| if a rule
  10617.     or to |next_p| if done@>;
  10618. goto move_past;
  10619. @ @<Output leaders in an hlist...@>=
  10620. begin leader_box:=leader_ptr(p);
  10621. if type(leader_box)=rule_node then
  10622.   begin rule_ht:=height(leader_box); rule_dp:=depth(leader_box);
  10623.   goto fin_rule;
  10624.   end;
  10625. leader_wd:=width(leader_box);
  10626. if (leader_wd>0)and(rule_wd>0) then
  10627.   begin rule_wd:=rule_wd+10; {compensate for floating-point rounding}
  10628.   edge:=cur_h+rule_wd; lx:=0;
  10629.   @<Let |cur_h| be the position of the first box, and set |leader_wd+lx|
  10630.     to the spacing between corresponding parts of boxes@>;
  10631.   while cur_h+leader_wd<=edge do
  10632.     @<Output a leader box at |cur_h|,
  10633.       then advance |cur_h| by |leader_wd+lx|@>;
  10634.   cur_h:=edge-10; goto next_p;
  10635.   end;
  10636. @ The calculations related to leaders require a bit of care. First, in the
  10637. case of |a_leaders| (aligned leaders), we want to move |cur_h| to
  10638. |left_edge| plus the smallest multiple of |leader_wd| for which the result
  10639. is not less than the current value of |cur_h|; i.e., |cur_h| should become
  10640. $|left_edge|+|leader_wd|\times\lceil
  10641. (|cur_h|-|left_edge|)/|leader_wd|\rceil$.  The program here should work in
  10642. all cases even though some implementations of \PASCAL\ give nonstandard
  10643. results for the |div| operation when |cur_h| is less than |left_edge|.
  10644. In the case of |c_leaders| (centered leaders), we want to increase |cur_h|
  10645. by half of the excess space not occupied by the leaders; and in the
  10646. case of |x_leaders| (expanded leaders) we increase |cur_h|
  10647. by $1/(q+1)$ of this excess space, where $q$ is the number of times the
  10648. leader box will be replicated. Slight inaccuracies in the division might
  10649. accumulate; half of this rounding error is placed at each end of the leaders.
  10650. @<Let |cur_h| be the position of the first box, ...@>=
  10651. if subtype(p)=a_leaders then
  10652.   begin save_h:=cur_h;
  10653.   cur_h:=left_edge+leader_wd*((cur_h-left_edge)@!div leader_wd);
  10654.   if cur_h<save_h then cur_h:=cur_h+leader_wd;
  10655.   end
  10656. else  begin lq:=rule_wd div leader_wd; {the number of box copies}
  10657.   lr:=rule_wd mod leader_wd; {the remaining space}
  10658.   if subtype(p)=c_leaders then cur_h:=cur_h+(lr div 2)
  10659.   else  begin lx:=(2*lr+lq+1) div (2*lq+2); {round|(lr/(lq+1))|}
  10660.     cur_h:=cur_h+((lr-(lq-1)*lx) div 2);
  10661.     end;
  10662.   end
  10663. @ The `\\{synch}' operations here are intended to decrease the number of
  10664. bytes needed to specify horizontal and vertical motion in the \.{DVI} output.
  10665. @<Output a leader box at |cur_h|, ...@>=
  10666. begin cur_v:=base_line+shift_amount(leader_box); synch_v; save_v:=dvi_v;@/
  10667. synch_h; save_h:=dvi_h; temp_ptr:=leader_box;
  10668. outer_doing_leaders:=doing_leaders; doing_leaders:=true;
  10669. if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
  10670. doing_leaders:=outer_doing_leaders;
  10671. dvi_v:=save_v; dvi_h:=save_h; cur_v:=base_line;
  10672. cur_h:=save_h+leader_wd+lx;
  10673. @ The |vlist_out| routine is similar to |hlist_out|, but a bit simpler.
  10674. @p procedure vlist_out; {output a |vlist_node| box}
  10675. label move_past, fin_rule, next_p;
  10676. var left_edge: scaled; {the left coordinate for this box}
  10677. @!top_edge: scaled; {the top coordinate for this box}
  10678. @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
  10679. @!this_box: pointer; {pointer to containing box}
  10680. @!g_order: glue_ord; {applicable order of infinity for glue}
  10681. @!g_sign: normal..shrinking; {selects type of glue}
  10682. @!p:pointer; {current position in the vlist}
  10683. @!save_loc:integer; {\.{DVI} byte location upon entry}
  10684. @!leader_box:pointer; {the leader box being replicated}
  10685. @!leader_ht:scaled; {height of leader box being replicated}
  10686. @!lx:scaled; {extra space between leader boxes}
  10687. @!outer_doing_leaders:boolean; {were we doing leaders?}
  10688. @!edge:scaled; {bottom boundary of leader space}
  10689. @!glue_temp:real; {glue value before rounding}
  10690. begin this_box:=temp_ptr; g_order:=glue_order(this_box);
  10691. g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
  10692. incr(cur_s);
  10693. if cur_s>0 then dvi_out(push);
  10694. if cur_s>max_push then max_push:=cur_s;
  10695. save_loc:=dvi_offset+dvi_ptr; left_edge:=cur_h; cur_v:=cur_v-height(this_box);
  10696. top_edge:=cur_v;
  10697. while p<>null do @<Output node |p| for |vlist_out| and move to the next node,
  10698.   maintaining the condition |cur_h=left_edge|@>;
  10699. prune_movements(save_loc);
  10700. if cur_s>0 then dvi_pop(save_loc);
  10701. decr(cur_s);
  10702. @ @<Output node |p| for |vlist_out|...@>=
  10703. begin if is_char_node(p) then confusion("vlistout")
  10704. @:this can't happen vlistout}{\quad vlistout@>
  10705. else @<Output the non-|char_node| |p| for |vlist_out|@>;
  10706. next_p:p:=link(p);
  10707. @ @<Output the non-|char_node| |p| for |vlist_out|@>=
  10708. begin case type(p) of
  10709. hlist_node,vlist_node:@<Output a box in a vlist@>;
  10710. rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
  10711.   goto fin_rule;
  10712.   end;
  10713. whatsit_node: @<Output the whatsit node |p| in a vlist@>;
  10714. glue_node: @<Move down or output leaders@>;
  10715. kern_node:cur_v:=cur_v+width(p);
  10716. othercases do_nothing
  10717. endcases;@/
  10718. goto next_p;
  10719. fin_rule: @<Output a rule in a vlist, |goto next_p|@>;
  10720. move_past: cur_v:=cur_v+rule_ht;
  10721. @ The |synch_v| here allows the \.{DVI} output to use one-byte commands
  10722. for adjusting |v| in most cases, since the baselineskip distance will
  10723. usually be constant.
  10724. @<Output a box in a vlist@>=
  10725. if list_ptr(p)=null then cur_v:=cur_v+height(p)+depth(p)
  10726. else  begin cur_v:=cur_v+height(p); synch_v;
  10727.   save_h:=dvi_h; save_v:=dvi_v;
  10728.   cur_h:=left_edge+shift_amount(p); {shift the box right}
  10729.   temp_ptr:=p;
  10730.   if type(p)=vlist_node then vlist_out@+else hlist_out;
  10731.   dvi_h:=save_h; dvi_v:=save_v;
  10732.   cur_v:=save_v+depth(p); cur_h:=left_edge;
  10733.   end
  10734. @ @<Output a rule in a vlist...@>=
  10735. if is_running(rule_wd) then rule_wd:=width(this_box);
  10736. rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
  10737. cur_v:=cur_v+rule_ht;
  10738. if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
  10739.   begin synch_h; synch_v;
  10740.   dvi_out(put_rule); dvi_four(rule_ht); dvi_four(rule_wd);
  10741.   end;
  10742. goto next_p
  10743. @ @<Move down or output leaders@>=
  10744. begin g:=glue_ptr(p); rule_ht:=width(g);
  10745. if g_sign<>normal then
  10746.   begin if g_sign=stretching then
  10747.     begin if stretch_order(g)=g_order then
  10748.       begin vet_glue(float(glue_set(this_box))*stretch(g));
  10749. @^real multiplication@>
  10750.       rule_ht:=rule_ht+round(glue_temp);
  10751.       end;
  10752.     end
  10753.   else if shrink_order(g)=g_order then
  10754.     begin vet_glue(float(glue_set(this_box))*shrink(g));
  10755.     rule_ht:=rule_ht-round(glue_temp);
  10756.     end;
  10757.   end;
  10758. if subtype(p)>=a_leaders then
  10759.   @<Output leaders in a vlist, |goto fin_rule| if a rule
  10760.     or to |next_p| if done@>;
  10761. goto move_past;
  10762. @ @<Output leaders in a vlist...@>=
  10763. begin leader_box:=leader_ptr(p);
  10764. if type(leader_box)=rule_node then
  10765.   begin rule_wd:=width(leader_box); rule_dp:=0;
  10766.   goto fin_rule;
  10767.   end;
  10768. leader_ht:=height(leader_box)+depth(leader_box);
  10769. if (leader_ht>0)and(rule_ht>0) then
  10770.   begin rule_ht:=rule_ht+10; {compensate for floating-point rounding}
  10771.   edge:=cur_v+rule_ht; lx:=0;
  10772.   @<Let |cur_v| be the position of the first box, and set |leader_ht+lx|
  10773.     to the spacing between corresponding parts of boxes@>;
  10774.   while cur_v+leader_ht<=edge do
  10775.     @<Output a leader box at |cur_v|,
  10776.       then advance |cur_v| by |leader_ht+lx|@>;
  10777.   cur_v:=edge-10; goto next_p;
  10778.   end;
  10779. @ @<Let |cur_v| be the position of the first box, ...@>=
  10780. if subtype(p)=a_leaders then
  10781.   begin save_v:=cur_v;
  10782.   cur_v:=top_edge+leader_ht*((cur_v-top_edge)@!div leader_ht);
  10783.   if cur_v<save_v then cur_v:=cur_v+leader_ht;
  10784.   end
  10785. else  begin lq:=rule_ht div leader_ht; {the number of box copies}
  10786.   lr:=rule_ht mod leader_ht; {the remaining space}
  10787.   if subtype(p)=c_leaders then cur_v:=cur_v+(lr div 2)
  10788.   else  begin lx:=(2*lr+lq+1) div (2*lq+2); {round|(lr/(lq+1))|}
  10789.     cur_v:=cur_v+((lr-(lq-1)*lx) div 2);
  10790.     end;
  10791.   end
  10792. @ When we reach this part of the program, |cur_v| indicates the top of a
  10793. leader box, not its baseline.
  10794. @<Output a leader box at |cur_v|, ...@>=
  10795. begin cur_h:=left_edge+shift_amount(leader_box); synch_h; save_h:=dvi_h;@/
  10796. cur_v:=cur_v+height(leader_box); synch_v; save_v:=dvi_v;
  10797. temp_ptr:=leader_box;
  10798. outer_doing_leaders:=doing_leaders; doing_leaders:=true;
  10799. if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
  10800. doing_leaders:=outer_doing_leaders;
  10801. dvi_v:=save_v; dvi_h:=save_h; cur_h:=left_edge;
  10802. cur_v:=save_v-height(leader_box)+leader_ht+lx;
  10803. @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
  10804. ready for the |ship_out| routine that gets them started in the first place.
  10805. @p procedure ship_out(@!p:pointer); {output the box |p|}
  10806. label done;
  10807. var page_loc:integer; {location of the current |bop|}
  10808. @!j,@!k:0..9; {indices to first ten count registers}
  10809. @!s:pool_pointer; {index into |str_pool|}
  10810. @!old_setting:0..max_selector; {saved |selector| setting}
  10811. begin if tracing_output>0 then
  10812.   begin print_nl(""); print_ln;
  10813.   print("Completed box being shipped out");
  10814. @.Completed box...@>
  10815.   end;
  10816. if term_offset>max_print_line-9 then print_ln
  10817. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  10818. print_char("["); j:=9;
  10819. while (count(j)=0)and(j>0) do decr(j);
  10820. for k:=0 to j do
  10821.   begin print_int(count(k));
  10822.   if k<j then print_char(".");
  10823.   end;
  10824. update_terminal;
  10825. if tracing_output>0 then
  10826.   begin print_char("]");
  10827.   begin_diagnostic; show_box(p); end_diagnostic(true);
  10828.   end;
  10829. @<Ship box |p| out@>;
  10830. if tracing_output<=0 then print_char("]");
  10831. dead_cycles:=0;
  10832. update_terminal; {progress report}
  10833. @<Flush the box from memory, showing statistics if requested@>;
  10834. @ @<Flush the box from memory, showing statistics if requested@>=
  10835. @!stat if tracing_stats>1 then
  10836.   begin print_nl("Memory usage before: ");
  10837. @.Memory usage...@>
  10838.   print_int(var_used); print_char("&");
  10839.   print_int(dyn_used); print_char(";");
  10840.   end;
  10841. tats@/
  10842. flush_node_list(p);
  10843. @!stat if tracing_stats>1 then
  10844.   begin print(" after: ");
  10845.   print_int(var_used); print_char("&");
  10846.   print_int(dyn_used); print("; still untouched: ");
  10847.   print_int(hi_mem_min-lo_mem_max-1); print_ln;
  10848.   end;
  10849. @ @<Ship box |p| out@>=
  10850. @<Update the values of |max_h| and |max_v|; but if the page is too large,
  10851.   |goto done|@>;
  10852. @<Initialize variables as |ship_out| begins@>;
  10853. page_loc:=dvi_offset+dvi_ptr;
  10854. dvi_out(bop);
  10855. for k:=0 to 9 do dvi_four(count(k));
  10856. dvi_four(last_bop); last_bop:=page_loc;
  10857. cur_v:=height(p)+v_offset; temp_ptr:=p;
  10858. if type(p)=vlist_node then vlist_out@+else hlist_out;
  10859. dvi_out(eop); incr(total_pages); cur_s:=-1;
  10860. done:
  10861. @ Sometimes the user will generate a huge page because other error messages
  10862. are being ignored. Such pages are not output to the \.{dvi} file, since they
  10863. may confuse the printing software.
  10864. @<Update the values of |max_h| and |max_v|; but if the page is too large...@>=
  10865. if (height(p)>max_dimen)or@|(depth(p)>max_dimen)or@|
  10866.    (height(p)+depth(p)+v_offset>max_dimen)or@|
  10867.    (width(p)+h_offset>max_dimen) then
  10868.   begin print_err("Huge page cannot be shipped out");
  10869. @.Huge page...@>
  10870.   help2("The page just created is more than 18 feet tall or")@/
  10871.    ("more than 18 feet wide, so I suspect something went wrong.");
  10872.   error;
  10873.   if tracing_output<=0 then
  10874.     begin begin_diagnostic;
  10875.     print_nl("The following box has been deleted:");
  10876. @.The following...deleted@>
  10877.     show_box(p);
  10878.     end_diagnostic(true);
  10879.     end;
  10880.   goto done;
  10881.   end;
  10882. if height(p)+depth(p)+v_offset>max_v then max_v:=height(p)+depth(p)+v_offset;
  10883. if width(p)+h_offset>max_h then max_h:=width(p)+h_offset
  10884. @ At the end of the program, we must finish things off by writing the
  10885. post\-amble. If |total_pages=0|, the \.{DVI} file was never opened.
  10886. If |total_pages>=65536|, the \.{DVI} file will lie.
  10887. An integer variable |k| will be declared for use by this routine.
  10888. @<Finish the \.{DVI} file@>=
  10889. while cur_s>-1 do
  10890.   begin if cur_s>0 then dvi_out(pop)
  10891.   else  begin dvi_out(eop); incr(total_pages);
  10892.     end;
  10893.   decr(cur_s);
  10894.   end;
  10895. if total_pages=0 then print_nl("No pages of output.")
  10896. @.No pages of output@>
  10897. else  begin dvi_out(post); {beginning of the postamble}
  10898.   dvi_four(last_bop); last_bop:=dvi_offset+dvi_ptr-5; {|post| location}
  10899.   dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
  10900.   prepare_mag; dvi_four(mag); {magnification factor}
  10901.   dvi_four(max_v); dvi_four(max_h);@/
  10902.   dvi_out(max_push div 256); dvi_out(max_push mod 256);@/
  10903.   dvi_out((total_pages div 256) mod 256); dvi_out(total_pages mod 256);@/
  10904.   @<Output the font definitions for all fonts that were used@>;
  10905.   dvi_out(post_post); dvi_four(last_bop); dvi_out(id_byte);@/
  10906.   k:=4+((dvi_buf_size-dvi_ptr) mod 4); {the number of 223's}
  10907.   while k>0 do
  10908.     begin dvi_out(223); decr(k);
  10909.     end;
  10910.   @<Empty the last bytes out of |dvi_buf|@>;
  10911.   print_nl("Output written on "); slow_print(output_file_name);
  10912. @.Output written on x@>
  10913.   print(" ("); print_int(total_pages); print(" page");
  10914.   if total_pages<>1 then print_char("s");
  10915.   print(", "); print_int(dvi_offset+dvi_ptr); print(" bytes).");
  10916.   b_close(dvi_file);
  10917.   end
  10918. @ @<Output the font definitions...@>=
  10919. while font_ptr>font_base do
  10920.   begin if font_used[font_ptr] then dvi_font_def(font_ptr);
  10921.   decr(font_ptr);
  10922.   end
  10923. @* \[33] Packaging.
  10924. We're essentially done with the parts of \TeX\ that are concerned with
  10925. the input (|get_next|) and the output (|ship_out|). So it's time to
  10926. get heavily into the remaining part, which does the real work of typesetting.
  10927. After lists are constructed, \TeX\ wraps them up and puts them into boxes.
  10928. Two major subroutines are given the responsibility for this task: |hpack|
  10929. applies to horizontal lists (hlists) and |vpack| applies to vertical lists
  10930. (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
  10931. of the resulting boxes, and to adjust the glue if one of those dimensions
  10932. is pre-specified. The computed sizes normally enclose all of the material
  10933. inside the new box; but some items may stick out if negative glue is used,
  10934. if the box is overfull, or if a \.{\\vbox} includes other boxes that have
  10935. been shifted left.
  10936. The subroutine call |hpack(p,w,m)| returns a pointer to an |hlist_node|
  10937. for a box containing the hlist that starts at |p|. Parameter |w| specifies
  10938. a width; and parameter |m| is either `|exactly|' or `|additional|'.  Thus,
  10939. |hpack(p,w,exactly)| produces a box whose width is exactly |w|, while
  10940. |hpack(p,w,additional)| yields a box whose width is the natural width plus
  10941. |w|.  It is convenient to define a macro called `|natural|' to cover the
  10942. most common case, so that we can say |hpack(p,natural)| to get a box that
  10943. has the natural width of list |p|.
  10944. Similarly, |vpack(p,w,m)| returns a pointer to a |vlist_node| for a
  10945. box containing the vlist that starts at |p|. In this case |w| represents
  10946. a height instead of a width; the parameter |m| is interpreted as in |hpack|.
  10947. @d exactly=0 {a box dimension is pre-specified}
  10948. @d additional=1 {a box dimension is increased from the natural one}
  10949. @d natural==0,additional {shorthand for parameters to |hpack| and |vpack|}
  10950. @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
  10951. like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
  10952. that `\.{\\hbox}' with no dimension following it is equivalent to
  10953. `\.{\\hbox} \.{spread} \.{0pt}'.  The |scan_spec| subroutine scans such
  10954. constructions in the user's input, including the mandatory left brace that
  10955. follows them, and it puts the specification onto |save_stack| so that the
  10956. desired box can later be obtained by executing the following code:
  10957. $$\vbox{\halign{#\hfil\cr
  10958. |save_ptr:=save_ptr-2;|\cr
  10959. |hpack(p,saved(1),saved(0)).|\cr}}$$
  10960. Special care is necessary to ensure that the special |save_stack| codes
  10961. are placed just below the new group code, because scanning can change
  10962. |save_stack| when \.{\\csname} appears.
  10963. @p procedure scan_spec(@!c:group_code;@!three_codes:boolean);
  10964.   {scans a box specification and left brace}
  10965. label found;
  10966. var @!s:integer; {temporarily saved value}
  10967. @!spec_code:exactly..additional;
  10968. begin if three_codes then s:=saved(0);
  10969. if scan_keyword("to") then spec_code:=exactly
  10970. @.to@>
  10971. else if scan_keyword("spread") then spec_code:=additional
  10972. @.spread@>
  10973. else  begin spec_code:=additional; cur_val:=0;
  10974.   goto found;
  10975.   end;
  10976. scan_normal_dimen;
  10977. found: if three_codes then
  10978.   begin saved(0):=s; incr(save_ptr);
  10979.   end;
  10980. saved(0):=spec_code; saved(1):=cur_val; save_ptr:=save_ptr+2;
  10981. new_save_level(c); scan_left_brace;
  10982. @ To figure out the glue setting, |hpack| and |vpack| determine how much
  10983. stretchability and shrinkability are present, considering all four orders
  10984. of infinity. The highest order of infinity that has a nonzero coefficient
  10985. is then used as if no other orders were present.
  10986. For example, suppose that the given list contains six glue nodes with
  10987. the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
  10988. Then the total is essentially 2fil; and if a total additional space of 6pt
  10989. is to be achieved by stretching, the actual amounts of stretch will be
  10990. 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
  10991. considered. (The `fill' glue is therefore not really stretching infinitely
  10992. with respect to `fil'; nobody would actually want that to happen.)
  10993. The arrays |total_stretch| and |total_shrink| are used to determine how much
  10994. glue of each kind is present. A global variable |last_badness| is used
  10995. to implement \.{\\badness}.
  10996. @<Glob...@>=
  10997. @!total_stretch, @!total_shrink: array[glue_ord] of scaled;
  10998.   {glue found by |hpack| or |vpack|}
  10999. @!last_badness:integer; {badness of the most recently packaged box}
  11000. @ If the global variable |adjust_tail| is non-null, the |hpack| routine
  11001. also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
  11002. items and appends the resulting material onto the list that ends at
  11003. location |adjust_tail|.
  11004. @< Glob...@>=
  11005. @!adjust_tail:pointer; {tail of adjustment list}
  11006. @ @<Set init...@>=adjust_tail:=null; last_badness:=0;
  11007. @ Here now is |hpack|, which contains few if any surprises.
  11008. @p function hpack(@!p:pointer;@!w:scaled;@!m:small_number):pointer;
  11009. label reswitch, common_ending, exit;
  11010. var r:pointer; {the box node that will be returned}
  11011. @!q:pointer; {trails behind |p|}
  11012. @!h,@!d,@!x:scaled; {height, depth, and natural width}
  11013. @!s:scaled; {shift amount}
  11014. @!g:pointer; {points to a glue specification}
  11015. @!o:glue_ord; {order of infinity}
  11016. @!f:internal_font_number; {the font in a |char_node|}
  11017. @!i:four_quarters; {font information about a |char_node|}
  11018. @!hd:eight_bits; {height and depth indices for a character}
  11019. begin last_badness:=0; r:=get_node(box_node_size); type(r):=hlist_node;
  11020. subtype(r):=min_quarterword; shift_amount(r):=0;
  11021. q:=r+list_offset; link(q):=p;@/
  11022. h:=0; @<Clear dimensions to zero@>;
  11023. while p<>null do @<Examine node |p| in the hlist, taking account of its effect
  11024.   on the dimensions of the new box, or moving it to the adjustment list;
  11025.   then advance |p| to the next node@>;
  11026. if adjust_tail<>null then link(adjust_tail):=null;
  11027. height(r):=h; depth(r):=d;@/
  11028. @<Determine the value of |width(r)| and the appropriate glue setting;
  11029.   then |return| or |goto common_ending|@>;
  11030. common_ending: @<Finish issuing a diagnostic message
  11031.       for an overfull or underfull hbox@>;
  11032. exit: hpack:=r;
  11033. @ @<Clear dimensions to zero@>=
  11034. d:=0; x:=0;
  11035. total_stretch[normal]:=0; total_shrink[normal]:=0;
  11036. total_stretch[fil]:=0; total_shrink[fil]:=0;
  11037. total_stretch[fill]:=0; total_shrink[fill]:=0;
  11038. total_stretch[filll]:=0; total_shrink[filll]:=0
  11039. @ @<Examine node |p| in the hlist, taking account of its effect...@>=
  11040. @^inner loop@>
  11041. begin reswitch: while is_char_node(p) do
  11042.   @<Incorporate character dimensions into the dimensions of
  11043.     the hbox that will contain~it, then move to the next node@>;
  11044. if p<>null then
  11045.   begin case type(p) of
  11046.   hlist_node,vlist_node,rule_node,unset_node:
  11047.     @<Incorporate box dimensions into the dimensions of
  11048.       the hbox that will contain~it@>;
  11049.   ins_node,mark_node,adjust_node: if adjust_tail<>null then
  11050.     @<Transfer node |p| to the adjustment list@>;
  11051.   whatsit_node:@<Incorporate a whatsit node into an hbox@>;
  11052.   glue_node:@<Incorporate glue into the horizontal totals@>;
  11053.   kern_node,math_node: x:=x+width(p);
  11054.   ligature_node: @<Make node |p| look like a |char_node|
  11055.     and |goto reswitch|@>;
  11056.   othercases do_nothing
  11057.   endcases;@/
  11058.   p:=link(p);
  11059.   end;
  11060. @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
  11061. begin mem[lig_trick]:=mem[lig_char(p)]; link(lig_trick):=link(p);
  11062. p:=lig_trick; goto reswitch;
  11063. @ The code here implicitly uses the fact that running dimensions are
  11064. indicated by |null_flag|, which will be ignored in the calculations
  11065. because it is a highly negative number.
  11066. @<Incorporate box dimensions into the dimensions of the hbox...@>=
  11067. begin x:=x+width(p);
  11068. if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
  11069. if height(p)-s>h then h:=height(p)-s;
  11070. if depth(p)+s>d then d:=depth(p)+s;
  11071. @ The following code is part of \TeX's inner loop; i.e., adding another
  11072. character of text to the user's input will cause each of these instructions
  11073. to be exercised one more time.
  11074. @^inner loop@>
  11075. @<Incorporate character dimensions into the dimensions of the hbox...@>=
  11076. begin f:=font(p); i:=char_info(f)(character(p)); hd:=height_depth(i);
  11077. x:=x+char_width(f)(i);@/
  11078. s:=char_height(f)(hd);@+if s>h then h:=s;
  11079. s:=char_depth(f)(hd);@+if s>d then d:=s;
  11080. p:=link(p);
  11081. @ Although node |q| is not necessarily the immediate predecessor of node |p|,
  11082. it always points to some node in the list preceding |p|. Thus, we can delete
  11083. nodes by moving |q| when necessary. The algorithm takes linear time, and the
  11084. extra computation does not intrude on the inner loop unless it is necessary
  11085. to make a deletion.
  11086. @<Transfer node |p| to the adjustment list@>=
  11087. begin while link(q)<>p do q:=link(q);
  11088. if type(p)=adjust_node then
  11089.   begin link(adjust_tail):=adjust_ptr(p);
  11090.   while link(adjust_tail)<>null do adjust_tail:=link(adjust_tail);
  11091.   p:=link(p); free_node(link(q),small_node_size);
  11092.   end
  11093. else  begin link(adjust_tail):=p; adjust_tail:=p; p:=link(p);
  11094.   end;
  11095. link(q):=p; p:=q;
  11096. @ @<Incorporate glue into the horizontal totals@>=
  11097. begin g:=glue_ptr(p); x:=x+width(g);@/
  11098. o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
  11099. o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
  11100. if subtype(p)>=a_leaders then
  11101.   begin g:=leader_ptr(p);
  11102.   if height(g)>h then h:=height(g);
  11103.   if depth(g)>d then d:=depth(g);
  11104.   end;
  11105. @ When we get to the present part of the program, |x| is the natural width
  11106. of the box being packaged.
  11107. @<Determine the value of |width(r)| and the appropriate glue setting...@>=
  11108. if m=additional then w:=x+w;
  11109. width(r):=w; x:=w-x; {now |x| is the excess to be made up}
  11110. if x=0 then
  11111.   begin glue_sign(r):=normal; glue_order(r):=normal;
  11112.   set_glue_ratio_zero(glue_set(r));
  11113.   return;
  11114.   end
  11115. else if x>0 then @<Determine horizontal glue stretch setting, then |return|
  11116.     or \hbox{|goto common_ending|}@>
  11117. else @<Determine horizontal glue shrink setting, then |return|
  11118.     or \hbox{|goto common_ending|}@>
  11119. @ @<Determine horizontal glue stretch setting...@>=
  11120. begin @<Determine the stretch order@>;
  11121. glue_order(r):=o; glue_sign(r):=stretching;
  11122. if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
  11123. @^real division@>
  11124. else  begin glue_sign(r):=normal;
  11125.   set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
  11126.   end;
  11127. if o=normal then if list_ptr(r)<>null then
  11128.   @<Report an underfull hbox and |goto common_ending|, if this box
  11129.     is sufficiently bad@>;
  11130. return;
  11131. @ @<Determine the stretch order@>=
  11132. if total_stretch[filll]<>0 then o:=filll
  11133. else if total_stretch[fill]<>0 then o:=fill
  11134. else if total_stretch[fil]<>0 then o:=fil
  11135. else o:=normal
  11136. @ @<Report an underfull hbox and |goto common_ending|, if...@>=
  11137. begin last_badness:=badness(x,total_stretch[normal]);
  11138. if last_badness>hbadness then
  11139.   begin print_ln;
  11140.   if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
  11141.   print(" \hbox (badness "); print_int(last_badness);
  11142. @.Underfull \\hbox...@>
  11143. @.Loose \\hbox...@>
  11144.   goto common_ending;
  11145.   end;
  11146. @ In order to provide a decent indication of where an overfull or underfull
  11147. box originated, we use a global variable |pack_begin_line| that is
  11148. set nonzero only when |hpack| is being called by the paragraph builder
  11149. or the alignment finishing routine.
  11150. @<Glob...@>=
  11151. @!pack_begin_line:integer; {source file line where the current paragraph
  11152.   or alignment began; a negative value denotes alignment}
  11153. @ @<Set init...@>=
  11154. pack_begin_line:=0;
  11155. @ @<Finish issuing a diagnostic message for an overfull or underfull hbox@>=
  11156. if output_active then print(") has occurred while \output is active")
  11157. else  begin if pack_begin_line<>0 then
  11158.     begin if pack_begin_line>0 then print(") in paragraph at lines ")
  11159.     else print(") in alignment at lines ");
  11160.     print_int(abs(pack_begin_line));
  11161.     print("--");
  11162.     end
  11163.   else print(") detected at line ");
  11164.   print_int(line);
  11165.   end;
  11166. print_ln;@/
  11167. font_in_short_display:=null_font; short_display(list_ptr(r)); print_ln;@/
  11168. begin_diagnostic; show_box(r); end_diagnostic(true)
  11169. @ @<Determine horizontal glue shrink setting...@>=
  11170. begin @<Determine the shrink order@>;
  11171. glue_order(r):=o; glue_sign(r):=shrinking;
  11172. if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
  11173. @^real division@>
  11174. else  begin glue_sign(r):=normal;
  11175.   set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
  11176.   end;
  11177. if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
  11178.   begin last_badness:=1000000;
  11179.   set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
  11180.   @<Report an overfull hbox and |goto common_ending|, if this box
  11181.     is sufficiently bad@>;
  11182.   end
  11183. else if o=normal then if list_ptr(r)<>null then
  11184.   @<Report a tight hbox and |goto common_ending|, if this box
  11185.     is sufficiently bad@>;
  11186. return;
  11187. @ @<Determine the shrink order@>=
  11188. if total_shrink[filll]<>0 then o:=filll
  11189. else if total_shrink[fill]<>0 then o:=fill
  11190. else if total_shrink[fil]<>0 then o:=fil
  11191. else o:=normal
  11192. @ @<Report an overfull hbox and |goto common_ending|, if...@>=
  11193. if (-x-total_shrink[normal]>hfuzz)or(hbadness<100) then
  11194.   begin if (overfull_rule>0)and(-x-total_shrink[normal]>hfuzz) then
  11195.     begin while link(q)<>null do q:=link(q);
  11196.     link(q):=new_rule;
  11197.     width(link(q)):=overfull_rule;
  11198.     end;
  11199.   print_ln; print_nl("Overfull \hbox (");
  11200. @.Overfull \\hbox...@>
  11201.   print_scaled(-x-total_shrink[normal]); print("pt too wide");
  11202.   goto common_ending;
  11203.   end
  11204. @ @<Report a tight hbox and |goto common_ending|, if...@>=
  11205. begin last_badness:=badness(-x,total_shrink[normal]);
  11206. if last_badness>hbadness then
  11207.   begin print_ln; print_nl("Tight \hbox (badness "); print_int(last_badness);
  11208. @.Tight \\hbox...@>
  11209.   goto common_ending;
  11210.   end;
  11211. @ The |vpack| subroutine is actually a special case of a slightly more
  11212. general routine called |vpackage|, which has four parameters. The fourth
  11213. parameter, which is |max_dimen| in the case of |vpack|, specifies the
  11214. maximum depth of the page box that is constructed. The depth is first
  11215. computed by the normal rules; if it exceeds this limit, the reference
  11216. point is simply moved down until the limiting depth is attained.
  11217. @d vpack(#)==vpackage(#,max_dimen) {special case of unconstrained depth}
  11218. @p function vpackage(@!p:pointer;@!h:scaled;@!m:small_number;@!l:scaled):
  11219.   pointer;
  11220. label common_ending, exit;
  11221. var r:pointer; {the box node that will be returned}
  11222. @!w,@!d,@!x:scaled; {width, depth, and natural height}
  11223. @!s:scaled; {shift amount}
  11224. @!g:pointer; {points to a glue specification}
  11225. @!o:glue_ord; {order of infinity}
  11226. begin last_badness:=0; r:=get_node(box_node_size); type(r):=vlist_node;
  11227. subtype(r):=min_quarterword; shift_amount(r):=0;
  11228. list_ptr(r):=p;@/
  11229. w:=0; @<Clear dimensions to zero@>;
  11230. while p<>null do @<Examine node |p| in the vlist, taking account of its effect
  11231.   on the dimensions of the new box; then advance |p| to the next node@>;
  11232. width(r):=w;
  11233. if d>l then
  11234.   begin x:=x+d-l; depth(r):=l;
  11235.   end
  11236. else depth(r):=d;
  11237. @<Determine the value of |height(r)| and the appropriate glue setting;
  11238.   then |return| or |goto common_ending|@>;
  11239. common_ending: @<Finish issuing a diagnostic message
  11240.       for an overfull or underfull vbox@>;
  11241. exit: vpackage:=r;
  11242. @ @<Examine node |p| in the vlist, taking account of its effect...@>=
  11243. begin if is_char_node(p) then confusion("vpack")
  11244. @:this can't happen vpack}{\quad vpack@>
  11245. else  case type(p) of
  11246.   hlist_node,vlist_node,rule_node,unset_node:
  11247.     @<Incorporate box dimensions into the dimensions of
  11248.       the vbox that will contain~it@>;
  11249.   whatsit_node:@<Incorporate a whatsit node into a vbox@>;
  11250.   glue_node: @<Incorporate glue into the vertical totals@>;
  11251.   kern_node: begin x:=x+d+width(p); d:=0;
  11252.     end;
  11253.   othercases do_nothing
  11254.   endcases;
  11255. p:=link(p);
  11256. @ @<Incorporate box dimensions into the dimensions of the vbox...@>=
  11257. begin x:=x+d+height(p); d:=depth(p);
  11258. if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
  11259. if width(p)+s>w then w:=width(p)+s;
  11260. @ @<Incorporate glue into the vertical totals@>=
  11261. begin x:=x+d; d:=0;@/
  11262. g:=glue_ptr(p); x:=x+width(g);@/
  11263. o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
  11264. o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
  11265. if subtype(p)>=a_leaders then
  11266.   begin g:=leader_ptr(p);
  11267.   if width(g)>w then w:=width(g);
  11268.   end;
  11269. @ When we get to the present part of the program, |x| is the natural height
  11270. of the box being packaged.
  11271. @<Determine the value of |height(r)| and the appropriate glue setting...@>=
  11272. if m=additional then h:=x+h;
  11273. height(r):=h; x:=h-x; {now |x| is the excess to be made up}
  11274. if x=0 then
  11275.   begin glue_sign(r):=normal; glue_order(r):=normal;
  11276.   set_glue_ratio_zero(glue_set(r));
  11277.   return;
  11278.   end
  11279. else if x>0 then @<Determine vertical glue stretch setting, then |return|
  11280.     or \hbox{|goto common_ending|}@>
  11281. else @<Determine vertical glue shrink setting, then |return|
  11282.     or \hbox{|goto common_ending|}@>
  11283. @ @<Determine vertical glue stretch setting...@>=
  11284. begin @<Determine the stretch order@>;
  11285. glue_order(r):=o; glue_sign(r):=stretching;
  11286. if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
  11287. @^real division@>
  11288. else  begin glue_sign(r):=normal;
  11289.   set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
  11290.   end;
  11291. if o=normal then if list_ptr(r)<>null then
  11292.   @<Report an underfull vbox and |goto common_ending|, if this box
  11293.     is sufficiently bad@>;
  11294. return;
  11295. @ @<Report an underfull vbox and |goto common_ending|, if...@>=
  11296. begin last_badness:=badness(x,total_stretch[normal]);
  11297. if last_badness>vbadness then
  11298.   begin print_ln;
  11299.   if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
  11300.   print(" \vbox (badness "); print_int(last_badness);
  11301. @.Underfull \\vbox...@>
  11302. @.Loose \\vbox...@>
  11303.   goto common_ending;
  11304.   end;
  11305. @ @<Finish issuing a diagnostic message for an overfull or underfull vbox@>=
  11306. if output_active then print(") has occurred while \output is active")
  11307. else  begin if pack_begin_line<>0 then {it's actually negative}
  11308.     begin print(") in alignment at lines ");
  11309.     print_int(abs(pack_begin_line));
  11310.     print("--");
  11311.     end
  11312.   else print(") detected at line ");
  11313.   print_int(line);
  11314.   print_ln;@/
  11315.   end;
  11316. begin_diagnostic; show_box(r); end_diagnostic(true)
  11317. @ @<Determine vertical glue shrink setting...@>=
  11318. begin @<Determine the shrink order@>;
  11319. glue_order(r):=o; glue_sign(r):=shrinking;
  11320. if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
  11321. @^real division@>
  11322. else  begin glue_sign(r):=normal;
  11323.   set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
  11324.   end;
  11325. if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
  11326.   begin last_badness:=1000000;
  11327.   set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
  11328.   @<Report an overfull vbox and |goto common_ending|, if this box
  11329.     is sufficiently bad@>;
  11330.   end
  11331. else if o=normal then if list_ptr(r)<>null then
  11332.   @<Report a tight vbox and |goto common_ending|, if this box
  11333.     is sufficiently bad@>;
  11334. return;
  11335. @ @<Report an overfull vbox and |goto common_ending|, if...@>=
  11336. if (-x-total_shrink[normal]>vfuzz)or(vbadness<100) then
  11337.   begin print_ln; print_nl("Overfull \vbox (");
  11338. @.Overfull \\vbox...@>
  11339.   print_scaled(-x-total_shrink[normal]); print("pt too high");
  11340.   goto common_ending;
  11341.   end
  11342. @ @<Report a tight vbox and |goto common_ending|, if...@>=
  11343. begin last_badness:=badness(-x,total_shrink[normal]);
  11344. if last_badness>vbadness then
  11345.   begin print_ln; print_nl("Tight \vbox (badness "); print_int(last_badness);
  11346. @.Tight \\vbox...@>
  11347.   goto common_ending;
  11348.   end;
  11349. @ When a box is being appended to the current vertical list, the
  11350. baselineskip calculation is handled by the |append_to_vlist| routine.
  11351. @p procedure append_to_vlist(@!b:pointer);
  11352. var d:scaled; {deficiency of space between baselines}
  11353. @!p:pointer; {a new glue specification}
  11354. begin if prev_depth>ignore_depth then
  11355.   begin d:=width(baseline_skip)-prev_depth-height(b);
  11356.   if d<line_skip_limit then p:=new_param_glue(line_skip_code)
  11357.   else  begin p:=new_skip_param(baseline_skip_code);
  11358.     width(temp_ptr):=d; {|temp_ptr=glue_ptr(p)|}
  11359.     end;
  11360.   link(tail):=p; tail:=p;
  11361.   end;
  11362. link(tail):=b; tail:=b; prev_depth:=depth(b);
  11363. @* \[34] Data structures for math mode.
  11364. When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
  11365. {\sl mlist}, which is essentially a tree structure representing that
  11366. formula.  An mlist is a linear sequence of items, but we can regard it as
  11367. a tree structure because mlists can appear within mlists. For example, many
  11368. of the entries can be subscripted or superscripted, and such ``scripts''
  11369. are mlists in their own right.
  11370. An entire formula is parsed into such a tree before any of the actual
  11371. typesetting is done, because the current style of type is usually not
  11372. known until the formula has been fully scanned. For example, when the
  11373. formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
  11374. that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
  11375. During the scanning process, each element of the mlist being built is
  11376. classified as a relation, a binary operator, an open parenthesis, etc.,
  11377. or as a construct like `\.{\\sqrt}' that must be built up. This classification
  11378. appears in the mlist data structure.
  11379. After a formula has been fully scanned, the mlist is converted to an hlist
  11380. so that it can be incorporated into the surrounding text. This conversion is
  11381. controlled by a recursive procedure that decides all of the appropriate
  11382. styles by a ``top-down'' process starting at the outermost level and working
  11383. in towards the subformulas. The formula is ultimately pasted together using
  11384. combinations of horizontal and vertical boxes, with glue and penalty nodes
  11385. inserted as necessary.
  11386. An mlist is represented internally as a linked list consisting chiefly
  11387. of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
  11388. similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
  11389. allowed to appear in mlists together with the noads; \TeX\ tells the difference
  11390. by means of the |type| field, since a noad's |type| is always greater than
  11391. that of a node. An mlist does not contain character nodes, hlist nodes, vlist
  11392. nodes, math nodes, ligature nodes, mark nodes, insert nodes, adjust nodes,
  11393. or unset nodes; in particular, each mlist item appears in the
  11394. variable-size part of |mem|, so the |type| field is always present.
  11395. @ Each noad is four or more words long. The first word contains the |type|
  11396. and |subtype| and |link| fields that are already so familiar to us; the
  11397. second, third, and fourth words are called the noad's |nucleus|, |subscr|,
  11398. and |supscr| fields.
  11399. Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
  11400. parsed into an mlist containing a single element called an |ord_noad|.
  11401. The |nucleus| of this noad is a representation of `\.x', the |subscr| is
  11402. empty, and the |supscr| is a representation of `\.2'.
  11403. The |nucleus|, |subscr|, and |supscr| fields are further broken into
  11404. subfields. If |p| points to a noad, and if |q| is one of its principal
  11405. fields (e.g., |q=subscr(p)|), there are several possibilities for the
  11406. subfields, depending on the |math_type| of |q|.
  11407. \yskip\hang|math_type(q)=math_char| means that |fam(q)| refers to one of
  11408. the sixteen font families, and |character(q)| is the number of a character
  11409. within a font of that family, as in a character node.
  11410. \yskip\hang|math_type(q)=math_text_char| is similar, but the character is
  11411. unsubscripted and unsuperscripted and it is followed immediately by another
  11412. character from the same font. (This |math_type| setting appears only
  11413. briefly during the processing; it is used to suppress unwanted italic
  11414. corrections.)
  11415. \yskip\hang|math_type(q)=empty| indicates a field with no value (the
  11416. corresponding attribute of noad |p| is not present).
  11417. \yskip\hang|math_type(q)=sub_box| means that |info(q)| points to a box
  11418. node (either an |hlist_node| or a |vlist_node|) that should be used as the
  11419. value of the field.  The |shift_amount| in the subsidiary box node is the
  11420. amount by which that box will be shifted downward.
  11421. \yskip\hang|math_type(q)=sub_mlist| means that |info(q)| points to
  11422. an mlist; the mlist must be converted to an hlist in order to obtain
  11423. the value of this field.
  11424. \yskip\noindent In the latter case, we might have |info(q)=null|. This
  11425. is not the same as |math_type(q)=empty|; for example, `\.{\$P\_\{\}\$}'
  11426. and `\.{\$P\$}' produce different results (the former will not have the
  11427. ``italic correction'' added to the width of |P|, but the ``script skip''
  11428. will be added).
  11429. The definitions of subfields given here are evidently wasteful of space,
  11430. since a halfword is being used for the |math_type| although only three
  11431. bits would be needed. However, there are hardly ever many noads present at
  11432. once, since they are soon converted to nodes that take up even more space,
  11433. so we can afford to represent them in whatever way simplifies the
  11434. programming.
  11435. @d noad_size=4 {number of words in a normal noad}
  11436. @d nucleus(#)==#+1 {the |nucleus| field of a noad}
  11437. @d supscr(#)==#+2 {the |supscr| field of a noad}
  11438. @d subscr(#)==#+3 {the |subscr| field of a noad}
  11439. @d math_type==link {a |halfword| in |mem|}
  11440. @d fam==font {a |quarterword| in |mem|}
  11441. @d math_char=1 {|math_type| when the attribute is simple}
  11442. @d sub_box=2 {|math_type| when the attribute is a box}
  11443. @d sub_mlist=3 {|math_type| when the attribute is a formula}
  11444. @d math_text_char=4 {|math_type| when italic correction is dubious}
  11445. @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Ope,
  11446. Clo, Pun, or Inn, for purposes of spacing and line breaking. An
  11447. |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
  11448. |punct_noad|, or |inner_noad| is used to represent portions of the various
  11449. types. For example, an `\.=' sign in a formula leads to the creation of a
  11450. |rel_noad| whose |nucleus| field is a representation of an equals sign
  11451. (usually |fam=0|, |character=@'75|).  A formula preceded by \.{\\mathrel}
  11452. also results in a |rel_noad|.  When a |rel_noad| is followed by an
  11453. |op_noad|, say, and possibly separated by one or more ordinary nodes (not
  11454. noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
  11455. just after the formula that corresponds to the |rel_noad|, unless there
  11456. already was a penalty immediately following; and a ``thick space'' will be
  11457. inserted just before the formula that corresponds to the |op_noad|.
  11458. A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
  11459. has a |subtype=normal|. The only exception is that an |op_noad| might
  11460. have |subtype=limits| or |no_limits|, if the normal positioning of
  11461. limits has been overridden for this operator.
  11462. @d ord_noad=unset_node+3 {|type| of a noad classified Ord}
  11463. @d op_noad=ord_noad+1 {|type| of a noad classified Op}
  11464. @d bin_noad=ord_noad+2 {|type| of a noad classified Bin}
  11465. @d rel_noad=ord_noad+3 {|type| of a noad classified Rel}
  11466. @d open_noad=ord_noad+4 {|type| of a noad classified Ope}
  11467. @d close_noad=ord_noad+5 {|type| of a noad classified Clo}
  11468. @d punct_noad=ord_noad+6 {|type| of a noad classified Pun}
  11469. @d inner_noad=ord_noad+7 {|type| of a noad classified Inn}
  11470. @d limits=1 {|subtype| of |op_noad| whose scripts are to be above, below}
  11471. @d no_limits=2 {|subtype| of |op_noad| whose scripts are to be normal}
  11472. @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
  11473. field, which usually represents a square root sign.
  11474. A |fraction_noad| is six words long; it has a |right_delimiter| field
  11475. as well as a |left_delimiter|.
  11476. Delimiter fields are of type |four_quarters|, and they have four subfields
  11477. called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
  11478. represent variable-size delimiters by giving the ``small'' and ``large''
  11479. starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
  11480. @:TeXbook}{\sl The \TeX book@>
  11481. A |fraction_noad| is actually quite different from all other noads. Not
  11482. only does it have six words, it has |thickness|, |denominator|, and
  11483. |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
  11484. |thickness| is a scaled value that tells how thick to make a fraction
  11485. rule; however, the special value |default_code| is used to stand for the
  11486. |default_rule_thickness| of the current size. The |numerator| and
  11487. |denominator| point to mlists that define a fraction; we always have
  11488. $$\hbox{|math_type(numerator)=math_type(denominator)=sub_mlist|}.$$ The
  11489. |left_delimiter| and |right_delimiter| fields specify delimiters that will
  11490. be placed at the left and right of the fraction. In this way, a
  11491. |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
  11492. \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
  11493.  \.{\\abovewithdelims}.
  11494. @d left_delimiter(#)==#+4 {first delimiter field of a noad}
  11495. @d right_delimiter(#)==#+5 {second delimiter field of a fraction noad}
  11496. @d radical_noad=inner_noad+1 {|type| of a noad for square roots}
  11497. @d radical_noad_size=5 {number of |mem| words in a radical noad}
  11498. @d fraction_noad=radical_noad+1 {|type| of a noad for generalized fractions}
  11499. @d fraction_noad_size=6 {number of |mem| words in a fraction noad}
  11500. @d small_fam(#)==mem[#].qqqq.b0 {|fam| for ``small'' delimiter}
  11501. @d small_char(#)==mem[#].qqqq.b1 {|character| for ``small'' delimiter}
  11502. @d large_fam(#)==mem[#].qqqq.b2 {|fam| for ``large'' delimiter}
  11503. @d large_char(#)==mem[#].qqqq.b3 {|character| for ``large'' delimiter}
  11504. @d thickness==width {|thickness| field in a fraction noad}
  11505. @d default_code==@'10000000000 {denotes |default_rule_thickness|}
  11506. @d numerator==supscr {|numerator| field in a fraction noad}
  11507. @d denominator==subscr {|denominator| field in a fraction noad}
  11508. @ The global variable |empty_field| is set up for initialization of empty
  11509. fields in new noads. Similarly, |null_delimiter| is for the initialization
  11510. of delimiter fields.
  11511. @<Glob...@>=
  11512. @!empty_field:two_halves;
  11513. @!null_delimiter:four_quarters;
  11514. @ @<Set init...@>=
  11515. empty_field.rh:=empty; empty_field.lh:=null;@/
  11516. null_delimiter.b0:=0; null_delimiter.b1:=min_quarterword;@/
  11517. null_delimiter.b2:=0; null_delimiter.b3:=min_quarterword;
  11518. @ The |new_noad| function creates an |ord_noad| that is completely null.
  11519. @p function new_noad:pointer;
  11520. var p:pointer;
  11521. begin p:=get_node(noad_size);
  11522. type(p):=ord_noad; subtype(p):=normal;
  11523. mem[nucleus(p)].hh:=empty_field;
  11524. mem[subscr(p)].hh:=empty_field;
  11525. mem[supscr(p)].hh:=empty_field;
  11526. new_noad:=p;
  11527. @ A few more kinds of noads will complete the set: An |under_noad| has its
  11528. nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
  11529. an accent over its nucleus; the accent character appears as
  11530. |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
  11531. centers its nucleus vertically with respect to the axis of the formula;
  11532. in such noads we always have |math_type(nucleus(p))=sub_box|.
  11533. And finally, we have |left_noad| and |right_noad| types, to implement
  11534. \TeX's \.{\\left} and \.{\\right}. The |nucleus| of such noads is
  11535. replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
  11536. a |left_noad| such that |delimiter(p)| holds the family and character
  11537. codes for all left parentheses. A |left_noad| never appears in an mlist
  11538. except as the first element, and a |right_noad| never appears in an mlist
  11539. except as the last element; furthermore, we either have both a |left_noad|
  11540. and a |right_noad|, or neither one is present. The |subscr| and |supscr|
  11541. fields are always |empty| in a |left_noad| and a |right_noad|.
  11542. @d under_noad=fraction_noad+1 {|type| of a noad for underlining}
  11543. @d over_noad=under_noad+1 {|type| of a noad for overlining}
  11544. @d accent_noad=over_noad+1 {|type| of a noad for accented subformulas}
  11545. @d accent_noad_size=5 {number of |mem| words in an accent noad}
  11546. @d accent_chr(#)==#+4 {the |accent_chr| field of an accent noad}
  11547. @d vcenter_noad=accent_noad+1 {|type| of a noad for \.{\\vcenter}}
  11548. @d left_noad=vcenter_noad+1 {|type| of a noad for \.{\\left}}
  11549. @d right_noad=left_noad+1 {|type| of a noad for \.{\\right}}
  11550. @d delimiter==nucleus {|delimiter| field in left and right noads}
  11551. @d scripts_allowed(#)==(type(#)>=ord_noad)and(type(#)<left_noad)
  11552. @ Math formulas can also contain instructions like \.{\\textstyle} that
  11553. override \TeX's normal style rules. A |style_node| is inserted into the
  11554. data structure to record such instructions; it is three words long, so it
  11555. is considered a node instead of a noad. The |subtype| is either |display_style|
  11556. or |text_style| or |script_style| or |script_script_style|. The
  11557. second and third words of a |style_node| are not used, but they are
  11558. present because a |choice_node| is converted to a |style_node|.
  11559. \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
  11560. |display_style|, \dots, |script_script_style|, and adds~1 to get the
  11561. ``cramped'' versions of these styles. This gives a numerical order that
  11562. is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
  11563. i.e., a smaller style has a larger numerical value.
  11564. @:TeXbook}{\sl The \TeX book@>
  11565. @d style_node=unset_node+1 {|type| of a style node}
  11566. @d style_node_size=3 {number of words in a style node}
  11567. @d display_style=0 {|subtype| for \.{\\displaystyle}}
  11568. @d text_style=2 {|subtype| for \.{\\textstyle}}
  11569. @d script_style=4 {|subtype| for \.{\\scriptstyle}}
  11570. @d script_script_style=6 {|subtype| for \.{\\scriptscriptstyle}}
  11571. @d cramped=1 {add this to an uncramped style if you want to cramp it}
  11572. @p function new_style(@!s:small_number):pointer; {create a style node}
  11573. var p:pointer; {the new node}
  11574. begin p:=get_node(style_node_size); type(p):=style_node;
  11575. subtype(p):=s; width(p):=0; depth(p):=0; {the |width| and |depth| are not used}
  11576. new_style:=p;
  11577. @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
  11578. has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
  11579. and |script_script_mlist| pointing to the mlists for each style.
  11580. @d choice_node=unset_node+2 {|type| of a choice node}
  11581. @d display_mlist(#)==info(#+1) {mlist to be used in display style}
  11582. @d text_mlist(#)==link(#+1) {mlist to be used in text style}
  11583. @d script_mlist(#)==info(#+2) {mlist to be used in script style}
  11584. @d script_script_mlist(#)==link(#+2) {mlist to be used in scriptscript style}
  11585. @p function new_choice:pointer; {create a choice node}
  11586. var p:pointer; {the new node}
  11587. begin p:=get_node(style_node_size); type(p):=choice_node;
  11588. subtype(p):=0; {the |subtype| is not used}
  11589. display_mlist(p):=null; text_mlist(p):=null; script_mlist(p):=null;
  11590. script_script_mlist(p):=null;
  11591. new_choice:=p;
  11592. @ Let's consider now the previously unwritten part of |show_node_list|
  11593. that displays the things that can only be present in mlists; this
  11594. program illustrates how to access the data structures just defined.
  11595. In the context of the following program, |p| points to a node or noad that
  11596. should be displayed, and the current string contains the ``recursion history''
  11597. that leads to this point. The recursion history consists of a dot for each
  11598. outer level in which |p| is subsidiary to some node, or in which |p| is
  11599. subsidiary to the |nucleus| field of some noad; the dot is replaced by
  11600. `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
  11601. or |supscr| or |denominator| or |numerator| fields of noads. For example,
  11602. the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
  11603. |x| in the (ridiculous) formula
  11604. `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
  11605. @<Cases of |show_node_list| that arise...@>=
  11606. style_node:print_style(subtype(p));
  11607. choice_node:@<Display choice node |p|@>;
  11608. ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
  11609.   radical_noad,over_noad,under_noad,vcenter_noad,accent_noad,
  11610.   left_noad,right_noad:@<Display normal noad |p|@>;
  11611. fraction_noad:@<Display fraction noad |p|@>;
  11612. @ Here are some simple routines used in the display of noads.
  11613. @<Declare procedures needed for displaying the elements of mlists@>=
  11614. procedure print_fam_and_char(@!p:pointer); {prints family and character}
  11615. begin print_esc("fam"); print_int(fam(p)); print_char(" ");
  11616. print_ASCII(qo(character(p)));
  11617. procedure print_delimiter(@!p:pointer); {prints a delimiter as 24-bit hex value}
  11618. var a:integer; {accumulator}
  11619. begin a:=small_fam(p)*256+qo(small_char(p));
  11620. a:=a*@"1000+large_fam(p)*256+qo(large_char(p));
  11621. if a<0 then print_int(a) {this should never happen}
  11622. else print_hex(a);
  11623. @ The next subroutine will descend to another level of recursion when a
  11624. subsidiary mlist needs to be displayed. The parameter |c| indicates what
  11625. character is to become part of the recursion history. An empty mlist is
  11626. distinguished from a field with |math_type(p)=empty|, because these are
  11627. not equivalent (as explained above).
  11628. @^recursion@>
  11629. @<Declare procedures needed for displaying...@>=
  11630. procedure@?show_info; forward;@t\2@>@?{|show_node_list(info(temp_ptr))|}
  11631. procedure print_subsidiary_data(@!p:pointer;@!c:ASCII_code);
  11632.   {display a noad field}
  11633. begin if cur_length>=depth_threshold then
  11634.   begin if math_type(p)<>empty then print(" []");
  11635.   end
  11636. else  begin append_char(c); {include |c| in the recursion history}
  11637.   temp_ptr:=p; {prepare for |show_info| if recursion is needed}
  11638.   case math_type(p) of
  11639.   math_char: begin print_ln; print_current_string; print_fam_and_char(p);
  11640.     end;
  11641.   sub_box: show_info; {recursive call}
  11642.   sub_mlist: if info(p)=null then
  11643.       begin print_ln; print_current_string; print("{}");
  11644.       end
  11645.     else show_info; {recursive call}
  11646.   othercases do_nothing {|empty|}
  11647.   endcases;@/
  11648.   flush_char; {remove |c| from the recursion history}
  11649.   end;
  11650. @ The inelegant introduction of |show_info| in the code above seems better
  11651. than the alternative of using \PASCAL's strange |forward| declaration for a
  11652. procedure with parameters. The \PASCAL\ convention about dropping parameters
  11653. from a post-|forward| procedure is, frankly, so intolerable to the author
  11654. of \TeX\ that he would rather stoop to communication via a global temporary
  11655. variable. (A similar stoopidity occurred with respect to |hlist_out| and
  11656. |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
  11657. @^Knuth, Donald Ervin@>
  11658. @:PASCAL}{\PASCAL@>
  11659. @p procedure show_info; {the reader will kindly forgive this}
  11660. begin show_node_list(info(temp_ptr));
  11661. @ @<Declare procedures needed for displaying...@>=
  11662. procedure print_style(@!c:integer);
  11663. begin case c div 2 of
  11664. 0: print_esc("displaystyle"); {|display_style=0|}
  11665. 1: print_esc("textstyle"); {|text_style=2|}
  11666. 2: print_esc("scriptstyle"); {|script_style=4|}
  11667. 3: print_esc("scriptscriptstyle"); {|script_script_style=6|}
  11668. othercases print("Unknown style!")
  11669. endcases;
  11670. @ @<Display choice node |p|@>=
  11671. begin print_esc("mathchoice");
  11672. append_char("D"); show_node_list(display_mlist(p)); flush_char;
  11673. append_char("T"); show_node_list(text_mlist(p)); flush_char;
  11674. append_char("S"); show_node_list(script_mlist(p)); flush_char;
  11675. append_char("s"); show_node_list(script_script_mlist(p)); flush_char;
  11676. @ @<Display normal noad |p|@>=
  11677. begin case type(p) of
  11678. ord_noad: print_esc("mathord");
  11679. op_noad: print_esc("mathop");
  11680. bin_noad: print_esc("mathbin");
  11681. rel_noad: print_esc("mathrel");
  11682. open_noad: print_esc("mathopen");
  11683. close_noad: print_esc("mathclose");
  11684. punct_noad: print_esc("mathpunct");
  11685. inner_noad: print_esc("mathinner");
  11686. over_noad: print_esc("overline");
  11687. under_noad: print_esc("underline");
  11688. vcenter_noad: print_esc("vcenter");
  11689. radical_noad: begin print_esc("radical"); print_delimiter(left_delimiter(p));
  11690.   end;
  11691. accent_noad: begin print_esc("accent"); print_fam_and_char(accent_chr(p));
  11692.   end;
  11693. left_noad: begin print_esc("left"); print_delimiter(nucleus(p));
  11694.   end;
  11695. right_noad: begin print_esc("right"); print_delimiter(nucleus(p));
  11696.   end;
  11697. if subtype(p)<>normal then
  11698.   if subtype(p)=limits then print_esc("limits")
  11699.   else print_esc("nolimits");
  11700. if type(p)<left_noad then print_subsidiary_data(nucleus(p),".");
  11701. print_subsidiary_data(supscr(p),"^");
  11702. print_subsidiary_data(subscr(p),"_");
  11703. @ @<Display fraction noad |p|@>=
  11704. begin print_esc("fraction, thickness ");
  11705. if thickness(p)=default_code then print("= default")
  11706. else print_scaled(thickness(p));
  11707. if (small_fam(left_delimiter(p))<>0)or@+
  11708.   (small_char(left_delimiter(p))<>min_quarterword)or@|
  11709.   (large_fam(left_delimiter(p))<>0)or@|
  11710.   (large_char(left_delimiter(p))<>min_quarterword) then
  11711.   begin print(", left-delimiter "); print_delimiter(left_delimiter(p));
  11712.   end;
  11713. if (small_fam(right_delimiter(p))<>0)or@|
  11714.   (small_char(right_delimiter(p))<>min_quarterword)or@|
  11715.   (large_fam(right_delimiter(p))<>0)or@|
  11716.   (large_char(right_delimiter(p))<>min_quarterword) then
  11717.   begin print(", right-delimiter "); print_delimiter(right_delimiter(p));
  11718.   end;
  11719. print_subsidiary_data(numerator(p),"\");
  11720. print_subsidiary_data(denominator(p),"/");
  11721. @ That which can be displayed can also be destroyed.
  11722. @<Cases of |flush_node_list| that arise...@>=
  11723. style_node: begin free_node(p,style_node_size); goto done;
  11724.   end;
  11725. choice_node:begin flush_node_list(display_mlist(p));
  11726.   flush_node_list(text_mlist(p));
  11727.   flush_node_list(script_mlist(p));
  11728.   flush_node_list(script_script_mlist(p));
  11729.   free_node(p,style_node_size); goto done;
  11730.   end;
  11731. ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
  11732.   radical_noad,over_noad,under_noad,vcenter_noad,accent_noad:@t@>@;@/
  11733.   begin if math_type(nucleus(p))>=sub_box then
  11734.     flush_node_list(info(nucleus(p)));
  11735.   if math_type(supscr(p))>=sub_box then
  11736.     flush_node_list(info(supscr(p)));
  11737.   if math_type(subscr(p))>=sub_box then
  11738.     flush_node_list(info(subscr(p)));
  11739.   if type(p)=radical_noad then free_node(p,radical_noad_size)
  11740.   else if type(p)=accent_noad then free_node(p,accent_noad_size)
  11741.   else free_node(p,noad_size);
  11742.   goto done;
  11743.   end;
  11744. left_noad,right_noad: begin free_node(p,noad_size); goto done;
  11745.   end;
  11746. fraction_noad: begin flush_node_list(info(numerator(p)));
  11747.   flush_node_list(info(denominator(p)));
  11748.   free_node(p,fraction_noad_size); goto done;
  11749.   end;
  11750. @* \[35] Subroutines for math mode.
  11751. In order to convert mlists to hlists, i.e., noads to nodes, we need several
  11752. subroutines that are conveniently dealt with now.
  11753. Let us first introduce the macros that make it easy to get at the parameters and
  11754. other font information. A size code, which is a multiple of 16, is added to a
  11755. family number to get an index into the table of internal font numbers
  11756. for each combination of family and size.  (Be alert: Size codes get
  11757. larger as the type gets smaller.)
  11758. @d text_size=0 {size code for the largest size in a family}
  11759. @d script_size=16 {size code for the medium size in a family}
  11760. @d script_script_size=32 {size code for the smallest size in a family}
  11761. @<Basic printing procedures@>=
  11762. procedure print_size(@!s:integer);
  11763. begin if s=0 then print_esc("textfont")
  11764. else if s=script_size then print_esc("scriptfont")
  11765. else print_esc("scriptscriptfont");
  11766. @ Before an mlist is converted to an hlist, \TeX\ makes sure that
  11767. the fonts in family~2 have enough parameters to be math-symbol
  11768. fonts, and that the fonts in family~3 have enough parameters to be
  11769. math-extension fonts. The math-symbol parameters are referred to by using the
  11770. following macros, which take a size code as their parameter; for example,
  11771. |num1(cur_size)| gives the value of the |num1| parameter for the current size.
  11772. @^parameters for symbols@>
  11773. @^font parameters@>
  11774. @d mathsy_end(#)==fam_fnt(2+#)]].sc
  11775. @d mathsy(#)==font_info[#+param_base[mathsy_end
  11776. @d math_x_height==mathsy(5) {height of `\.x'}
  11777. @d math_quad==mathsy(6) {\.{18mu}}
  11778. @d num1==mathsy(8) {numerator shift-up in display styles}
  11779. @d num2==mathsy(9) {numerator shift-up in non-display, non-\.{\\atop}}
  11780. @d num3==mathsy(10) {numerator shift-up in non-display \.{\\atop}}
  11781. @d denom1==mathsy(11) {denominator shift-down in display styles}
  11782. @d denom2==mathsy(12) {denominator shift-down in non-display styles}
  11783. @d sup1==mathsy(13) {superscript shift-up in uncramped display style}
  11784. @d sup2==mathsy(14) {superscript shift-up in uncramped non-display}
  11785. @d sup3==mathsy(15) {superscript shift-up in cramped styles}
  11786. @d sub1==mathsy(16) {subscript shift-down if superscript is absent}
  11787. @d sub2==mathsy(17) {subscript shift-down if superscript is present}
  11788. @d sup_drop==mathsy(18) {superscript baseline below top of large box}
  11789. @d sub_drop==mathsy(19) {subscript baseline below bottom of large box}
  11790. @d delim1==mathsy(20) {size of \.{\\atopwithdelims} delimiters
  11791.   in display styles}
  11792. @d delim2==mathsy(21) {size of \.{\\atopwithdelims} delimiters in non-displays}
  11793. @d axis_height==mathsy(22) {height of fraction lines above the baseline}
  11794. @d total_mathsy_params=22
  11795. @ The math-extension parameters have similar macros, but the size code is
  11796. omitted (since it is always |cur_size| when we refer to such parameters).
  11797. @^parameters for symbols@>
  11798. @^font parameters@>
  11799. @d mathex(#)==font_info[#+param_base[fam_fnt(3+cur_size)]].sc
  11800. @d default_rule_thickness==mathex(8) {thickness of \.{\\over} bars}
  11801. @d big_op_spacing1==mathex(9) {minimum clearance above a displayed op}
  11802. @d big_op_spacing2==mathex(10) {minimum clearance below a displayed op}
  11803. @d big_op_spacing3==mathex(11) {minimum baselineskip above displayed op}
  11804. @d big_op_spacing4==mathex(12) {minimum baselineskip below displayed op}
  11805. @d big_op_spacing5==mathex(13) {padding above and below displayed limits}
  11806. @d total_mathex_params=13
  11807. @ We also need to compute the change in style between mlists and their
  11808. subsidiaries. The following macros define the subsidiary style for
  11809. an overlined nucleus (|cramped_style|), for a subscript or a superscript
  11810. (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
  11811. or |denom_style|).
  11812. @d cramped_style(#)==2*(# div 2)+cramped {cramp the style}
  11813. @d sub_style(#)==2*(# div 4)+script_style+cramped {smaller and cramped}
  11814. @d sup_style(#)==2*(# div 4)+script_style+(# mod 2) {smaller}
  11815. @d num_style(#)==#+2-2*(# div 6) {smaller unless already script-script}
  11816. @d denom_style(#)==2*(# div 2)+cramped+2-2*(# div 6) {smaller, cramped}
  11817. @ When the style changes, the following piece of program computes associated
  11818. information:
  11819. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
  11820. begin if cur_style<script_style then cur_size:=text_size
  11821. else cur_size:=16*((cur_style-text_style) div 2);
  11822. cur_mu:=x_over_n(math_quad(cur_size),18);
  11823. @ Here is a function that returns a pointer to a rule node having a given
  11824. thickness |t|. The rule will extend horizontally to the boundary of the vlist
  11825. that eventually contains it.
  11826. @p function fraction_rule(@!t:scaled):pointer;
  11827.   {construct the bar for a fraction}
  11828. var p:pointer; {the new node}
  11829. begin p:=new_rule; height(p):=t; depth(p):=0; fraction_rule:=p;
  11830. @ The |overbar| function returns a pointer to a vlist box that consists of
  11831. a given box |b|, above which has been placed a kern of height |k| under a
  11832. fraction rule of thickness |t| under additional space of height |t|.
  11833. @p function overbar(@!b:pointer;@!k,@!t:scaled):pointer;
  11834. var p,@!q:pointer; {nodes being constructed}
  11835. begin p:=new_kern(k); link(p):=b; q:=fraction_rule(t); link(q):=p;
  11836. p:=new_kern(t); link(p):=q; overbar:=vpack(p,natural);
  11837. @ The |var_delimiter| function, which finds or constructs a sufficiently
  11838. large delimiter, is the most interesting of the auxiliary functions that
  11839. currently concern us. Given a pointer |d| to a delimiter field in some noad,
  11840. together with a size code |s| and a vertical distance |v|, this function
  11841. returns a pointer to a box that contains the smallest variant of |d| whose
  11842. height plus depth is |v| or more. (And if no variant is large enough, it
  11843. returns the largest available variant.) In particular, this routine will
  11844. construct arbitrarily large delimiters from extensible components, if
  11845. |d| leads to such characters.
  11846. The value returned is a box whose |shift_amount| has been set so that
  11847. the box is vertically centered with respect to the axis in the given size.
  11848. If a built-up symbol is returned, the height of the box before shifting
  11849. will be the height of its topmost component.
  11850. @p@t\4@>@<Declare subprocedures for |var_delimiter|@>
  11851. function var_delimiter(@!d:pointer;@!s:small_number;@!v:scaled):pointer;
  11852. label found,continue;
  11853. var b:pointer; {the box that will be constructed}
  11854. @!f,@!g: internal_font_number; {best-so-far and tentative font codes}
  11855. @!c,@!x,@!y: quarterword; {best-so-far and tentative character codes}
  11856. @!m,@!n: integer; {the number of extensible pieces}
  11857. @!u: scaled; {height-plus-depth of a tentative character}
  11858. @!w: scaled; {largest height-plus-depth so far}
  11859. @!q: four_quarters; {character info}
  11860. @!hd: eight_bits; {height-depth byte}
  11861. @!r: four_quarters; {extensible pieces}
  11862. @!z: small_number; {runs through font family members}
  11863. @!large_attempt: boolean; {are we trying the ``large'' variant?}
  11864. begin f:=null_font; w:=0; large_attempt:=false;
  11865. z:=small_fam(d); x:=small_char(d);
  11866. loop@+  begin @<Look at the variants of |(z,x)|; set |f| and |c| whenever
  11867.     a better character is found; |goto found| as soon as a
  11868.     large enough variant is encountered@>;
  11869.   if large_attempt then goto found; {there were none large enough}
  11870.   large_attempt:=true; z:=large_fam(d); x:=large_char(d);
  11871.   end;
  11872. found: if f<>null_font then
  11873.   @<Make variable |b| point to a box for |(f,c)|@>
  11874. else  begin b:=new_null_box;
  11875.   width(b):=null_delimiter_space; {use this width if no delimiter was found}
  11876.   end;
  11877. shift_amount(b):=half(height(b)-depth(b)) - axis_height(s);
  11878. var_delimiter:=b;
  11879. @ The search process is complicated slightly by the facts that some of the
  11880. characters might not be present in some of the fonts, and they might not
  11881. be probed in increasing order of height.
  11882. @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
  11883. if (z<>0)or(x<>min_quarterword) then
  11884.   begin z:=z+s+16;
  11885.   repeat z:=z-16; g:=fam_fnt(z);
  11886.   if g<>null_font then
  11887.     @<Look at the list of characters starting with |x| in
  11888.       font |g|; set |f| and |c| whenever
  11889.       a better character is found; |goto found| as soon as a
  11890.       large enough variant is encountered@>;
  11891.   until z<16;
  11892.   end
  11893. @ @<Look at the list of characters starting with |x|...@>=
  11894. begin y:=x;
  11895. if (qo(y)>=font_bc[g])and(qo(y)<=font_ec[g]) then
  11896.   begin continue: q:=char_info(g)(y);
  11897.   if char_exists(q) then
  11898.     begin if char_tag(q)=ext_tag then
  11899.       begin f:=g; c:=y; goto found;
  11900.       end;
  11901.     hd:=height_depth(q);
  11902.     u:=char_height(g)(hd)+char_depth(g)(hd);
  11903.     if u>w then
  11904.       begin f:=g; c:=y; w:=u;
  11905.       if u>=v then goto found;
  11906.       end;
  11907.     if char_tag(q)=list_tag then
  11908.       begin y:=rem_byte(q); goto continue;
  11909.       end;
  11910.     end;
  11911.   end;
  11912. @ Here is a subroutine that creates a new box, whose list contains a
  11913. single character, and whose width includes the italic correction for
  11914. that character. The height or depth of the box will be negative, if
  11915. the height or depth of the character is negative; thus, this routine
  11916. may deliver a slightly different result than |hpack| would produce.
  11917. @<Declare subprocedures for |var_delimiter|@>=
  11918. function char_box(@!f:internal_font_number;@!c:quarterword):pointer;
  11919. var q:four_quarters;
  11920. @!hd:eight_bits; {|height_depth| byte}
  11921. @!b,@!p:pointer; {the new box and its character node}
  11922. begin q:=char_info(f)(c); hd:=height_depth(q);
  11923. b:=new_null_box; width(b):=char_width(f)(q)+char_italic(f)(q);
  11924. height(b):=char_height(f)(hd); depth(b):=char_depth(f)(hd);
  11925. p:=get_avail; character(p):=c; font(p):=f; list_ptr(b):=p; char_box:=b;
  11926. @ When the following code is executed, |char_tag(q)| will be equal to
  11927. |ext_tag| if and only if a built-up symbol is supposed to be returned.
  11928. @<Make variable |b| point to a box for |(f,c)|@>=
  11929. if char_tag(q)=ext_tag then
  11930.   @<Construct an extensible character in a new box |b|,
  11931.     using recipe |rem_byte(q)| and font |f|@>
  11932. else b:=char_box(f,c)
  11933. @ When we build an extensible character, it's handy to have the
  11934. following subroutine, which puts a given character on top
  11935. of the characters already in box |b|:
  11936. @<Declare subprocedures for |var_delimiter|@>=
  11937. procedure stack_into_box(@!b:pointer;@!f:internal_font_number;
  11938.   @!c:quarterword);
  11939. var p:pointer; {new node placed into |b|}
  11940. begin p:=char_box(f,c); link(p):=list_ptr(b); list_ptr(b):=p;
  11941. height(b):=height(p);
  11942. @ Another handy subroutine computes the height plus depth of
  11943. a given character:
  11944. @<Declare subprocedures for |var_delimiter|@>=
  11945. function height_plus_depth(@!f:internal_font_number;@!c:quarterword):scaled;
  11946. var q:four_quarters;
  11947. @!hd:eight_bits; {|height_depth| byte}
  11948. begin q:=char_info(f)(c); hd:=height_depth(q);
  11949. height_plus_depth:=char_height(f)(hd)+char_depth(f)(hd);
  11950. @ @<Construct an extensible...@>=
  11951. begin b:=new_null_box;
  11952. type(b):=vlist_node;
  11953. r:=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
  11954. @<Compute the minimum suitable height, |w|, and the corresponding
  11955.   number of extension steps, |n|; also set |width(b)|@>;
  11956. c:=ext_bot(r);
  11957. if c<>min_quarterword then stack_into_box(b,f,c);
  11958. c:=ext_rep(r);
  11959. for m:=1 to n do stack_into_box(b,f,c);
  11960. c:=ext_mid(r);
  11961. if c<>min_quarterword then
  11962.   begin stack_into_box(b,f,c); c:=ext_rep(r);
  11963.   for m:=1 to n do stack_into_box(b,f,c);
  11964.   end;
  11965. c:=ext_top(r);
  11966. if c<>min_quarterword then stack_into_box(b,f,c);
  11967. depth(b):=w-height(b);
  11968. @ The width of an extensible character is the width of the repeatable
  11969. module. If this module does not have positive height plus depth,
  11970. we don't use any copies of it, otherwise we use as few as possible
  11971. (in groups of two if there is a middle part).
  11972. @<Compute the minimum suitable height, |w|, and...@>=
  11973. c:=ext_rep(r); u:=height_plus_depth(f,c);
  11974. w:=0; q:=char_info(f)(c); width(b):=char_width(f)(q)+char_italic(f)(q);@/
  11975. c:=ext_bot(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11976. c:=ext_mid(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11977. c:=ext_top(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11978. n:=0;
  11979. if u>0 then while w<v do
  11980.   begin w:=w+u; incr(n);
  11981.   if ext_mid(r)<>min_quarterword then w:=w+u;
  11982.   end
  11983. @ The next subroutine is much simpler; it is used for numerators and
  11984. denominators of fractions as well as for displayed operators and
  11985. their limits above and below. It takes a given box~|b| and
  11986. changes it so that the new box is centered in a box of width~|w|.
  11987. The centering is done by putting \.{\\hss} glue at the left and right
  11988. of the list inside |b|, then packaging the new box; thus, the
  11989. actual box might not really be centered, if it already contains
  11990. infinite glue.
  11991. The given box might contain a single character whose italic correction
  11992. has been added to the width of the box; in this case a compensating
  11993. kern is inserted.
  11994. @p function rebox(@!b:pointer;@!w:scaled):pointer;
  11995. var p:pointer; {temporary register for list manipulation}
  11996. @!f:internal_font_number; {font in a one-character box}
  11997. @!v:scaled; {width of a character without italic correction}
  11998. begin if (width(b)<>w)and(list_ptr(b)<>null) then
  11999.   begin if type(b)=vlist_node then b:=hpack(b,natural);
  12000.   p:=list_ptr(b);
  12001.   if (is_char_node(p))and(link(p)=null) then
  12002.     begin f:=font(p); v:=char_width(f)(char_info(f)(character(p)));
  12003.     if v<>width(b) then link(p):=new_kern(width(b)-v);
  12004.     end;
  12005.   free_node(b,box_node_size);
  12006.   b:=new_glue(ss_glue); link(b):=p;
  12007.   while link(p)<>null do p:=link(p);
  12008.   link(p):=new_glue(ss_glue);
  12009.   rebox:=hpack(b,w,exactly);
  12010.   end
  12011. else  begin width(b):=w; rebox:=b;
  12012.   end;
  12013. @ Here is a subroutine that creates a new glue specification from another
  12014. one that is expressed in `\.{mu}', given the value of the math unit.
  12015. @d mu_mult(#)==nx_plus_y(n,#,xn_over_d(#,f,@'200000))
  12016. @p function math_glue(@!g:pointer;@!m:scaled):pointer;
  12017. var p:pointer; {the new glue specification}
  12018. @!n:integer; {integer part of |m|}
  12019. @!f:scaled; {fraction part of |m|}
  12020. begin n:=x_over_n(m,@'200000); f:=remainder;@/
  12021. if f<0 then
  12022.   begin decr(n); f:=f+@'200000;
  12023.   end;
  12024. p:=get_node(glue_spec_size);
  12025. width(p):=mu_mult(width(g)); {convert \.{mu} to \.{pt}}
  12026. stretch_order(p):=stretch_order(g);
  12027. if stretch_order(p)=normal then stretch(p):=mu_mult(stretch(g))
  12028. else stretch(p):=stretch(g);
  12029. shrink_order(p):=shrink_order(g);
  12030. if shrink_order(p)=normal then shrink(p):=mu_mult(shrink(g))
  12031. else shrink(p):=shrink(g);
  12032. math_glue:=p;
  12033. @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
  12034. the value of the math unit.
  12035. @p procedure math_kern(@!p:pointer;@!m:scaled);
  12036. var @!n:integer; {integer part of |m|}
  12037. @!f:scaled; {fraction part of |m|}
  12038. begin if subtype(p)=mu_glue then
  12039.   begin n:=x_over_n(m,@'200000); f:=remainder;@/
  12040.   if f<0 then
  12041.     begin decr(n); f:=f+@'200000;
  12042.     end;
  12043.   width(p):=mu_mult(width(p)); subtype(p):=explicit;
  12044.   end;
  12045. @ Sometimes it is necessary to destroy an mlist. The following
  12046. subroutine empties the current list, assuming that |abs(mode)=mmode|.
  12047. @p procedure flush_math;
  12048. begin flush_node_list(link(head)); flush_node_list(incompleat_noad);
  12049. link(head):=null; tail:=head; incompleat_noad:=null;
  12050. @* \[36] Typesetting math formulas.
  12051. \TeX's most important routine for dealing with formulas is called
  12052. |mlist_to_hlist|.  After a formula has been scanned and represented as an
  12053. mlist, this routine converts it to an hlist that can be placed into a box
  12054. or incorporated into the text of a paragraph. There are three implicit
  12055. parameters, passed in global variables: |cur_mlist| points to the first
  12056. node or noad in the given mlist (and it might be |null|); |cur_style| is a
  12057. style code; and |mlist_penalties| is |true| if penalty nodes for potential
  12058. line breaks are to be inserted into the resulting hlist. After
  12059. |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
  12060. Since mlists can be inside mlists, the procedure is recursive. And since this
  12061. is not part of \TeX's inner loop, the program has been written in a manner
  12062. that stresses compactness over efficiency.
  12063. @^recursion@>
  12064. @<Glob...@>=
  12065. @!cur_mlist:pointer; {beginning of mlist to be translated}
  12066. @!cur_style:small_number; {style code at current place in the list}
  12067. @!cur_size:small_number; {size code corresponding to |cur_style|}
  12068. @!cur_mu:scaled; {the math unit width corresponding to |cur_size|}
  12069. @!mlist_penalties:boolean; {should |mlist_to_hlist| insert penalties?}
  12070. @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
  12071. called |clean_box| that puts a given noad field into a box using a given
  12072. math style; |mlist_to_hlist| can call |clean_box|, which can call
  12073. |mlist_to_hlist|.
  12074. @^recursion@>
  12075. The box returned by |clean_box| is ``clean'' in the
  12076. sense that its |shift_amount| is zero.
  12077. @p procedure@?mlist_to_hlist; forward;@t\2@>@/
  12078. function clean_box(@!p:pointer;@!s:small_number):pointer;
  12079. label found;
  12080. var q:pointer; {beginning of a list to be boxed}
  12081. @!save_style:small_number; {|cur_style| to be restored}
  12082. @!x:pointer; {box to be returned}
  12083. @!r:pointer; {temporary pointer}
  12084. begin case math_type(p) of
  12085. math_char: begin cur_mlist:=new_noad; mem[nucleus(cur_mlist)]:=mem[p];
  12086.   end;
  12087. sub_box: begin q:=info(p); goto found;
  12088.   end;
  12089. sub_mlist: cur_mlist:=info(p);
  12090. othercases begin q:=new_null_box; goto found;
  12091.   end
  12092. endcases;@/
  12093. save_style:=cur_style; cur_style:=s; mlist_penalties:=false;@/
  12094. mlist_to_hlist; q:=link(temp_head); {recursive call}
  12095. cur_style:=save_style; {restore the style}
  12096. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12097. found: if is_char_node(q)or(q=null) then x:=hpack(q,natural)
  12098.   else if (link(q)=null)and(type(q)<=vlist_node)and(shift_amount(q)=0) then
  12099.     x:=q {it's already clean}
  12100.   else x:=hpack(q,natural);
  12101. @<Simplify a trivial box@>;
  12102. clean_box:=x;
  12103. @ Here we save memory space in a common case.
  12104. @<Simplify a trivial box@>=
  12105. q:=list_ptr(x);
  12106. if is_char_node(q) then
  12107.   begin r:=link(q);
  12108.   if r<>null then if link(r)=null then
  12109.    if not is_char_node(r) then if type(r)=kern_node then
  12110.     begin free_node(r,small_node_size); link(q):=null;
  12111.     end;
  12112.   end
  12113. @ It is convenient to have a procedure that converts a |math_char|
  12114. field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
  12115. and |cur_i| to the font code, character code, and character information bytes of
  12116. a given noad field. It also takes care of issuing error messages for
  12117. nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
  12118. after |fetch| has acted, and the field will also have been reset to |empty|.
  12119. @p procedure fetch(@!a:pointer); {unpack the |math_char| field |a|}
  12120. begin cur_c:=character(a); cur_f:=fam_fnt(fam(a)+cur_size);
  12121. if cur_f=null_font then
  12122.   @<Complain about an undefined family and set |cur_i| null@>
  12123. else  begin if (qo(cur_c)>=font_bc[cur_f])and(qo(cur_c)<=font_ec[cur_f]) then
  12124.     cur_i:=char_info(cur_f)(cur_c)
  12125.   else cur_i:=null_character;
  12126.   if not(char_exists(cur_i)) then
  12127.     begin char_warning(cur_f,qo(cur_c));
  12128.     math_type(a):=empty;
  12129.     end;
  12130.   end;
  12131. @ @<Complain about an undefined family...@>=
  12132. begin print_err(""); print_size(cur_size); print_char(" ");
  12133. print_int(fam(a)); print(" is undefined (character ");
  12134. print_ASCII(qo(cur_c)); print_char(")");
  12135. help4("Somewhere in the math formula just ended, you used the")@/
  12136. ("stated character from an undefined font family. For example,")@/
  12137. ("plain TeX doesn't allow \it or \sl in subscripts. Proceed,")@/
  12138. ("and I'll try to forget that I needed that character.");
  12139. error; cur_i:=null_character; math_type(a):=empty;
  12140. @ The outputs of |fetch| are placed in global variables.
  12141. @<Glob...@>=
  12142. @!cur_f:internal_font_number; {the |font| field of a |math_char|}
  12143. @!cur_c:quarterword; {the |character| field of a |math_char|}
  12144. @!cur_i:four_quarters; {the |char_info| of a |math_char|,
  12145.   or a lig/kern instruction}
  12146. @ We need to do a lot of different things, so |mlist_to_hlist| makes two
  12147. passes over the given mlist.
  12148. The first pass does most of the processing: It removes ``mu'' spacing from
  12149. glue, it recursively evaluates all subsidiary mlists so that only the
  12150. top-level mlist remains to be handled, it puts fractions and square roots
  12151. and such things into boxes, it attaches subscripts and superscripts, and
  12152. it computes the overall height and depth of the top-level mlist so that
  12153. the size of delimiters for a |left_noad| and a |right_noad| will be known.
  12154. The hlist resulting from each noad is recorded in that noad's |new_hlist|
  12155. field, an integer field that replaces the |nucleus| or |thickness|.
  12156. @^recursion@>
  12157. The second pass eliminates all noads and inserts the correct glue and
  12158. penalties between nodes.
  12159. @d new_hlist(#)==mem[nucleus(#)].int {the translation of an mlist}
  12160. @ Here is the overall plan of |mlist_to_hlist|, and the list of its
  12161. local variables.
  12162. @d done_with_noad=80 {go here when a noad has been fully translated}
  12163. @d done_with_node=81 {go here when a node has been fully converted}
  12164. @d check_dimensions=82 {go here to update |max_h| and |max_d|}
  12165. @d delete_q=83 {go here to delete |q| and move to the next node}
  12166. @p@t\4@>@<Declare math construction procedures@>
  12167. procedure mlist_to_hlist;
  12168. label reswitch, check_dimensions, done_with_noad, done_with_node, delete_q,
  12169.   done;
  12170. var mlist:pointer; {beginning of the given list}
  12171. @!penalties:boolean; {should penalty nodes be inserted?}
  12172. @!style:small_number; {the given style}
  12173. @!save_style:small_number; {holds |cur_style| during recursion}
  12174. @!q:pointer; {runs through the mlist}
  12175. @!r:pointer; {the most recent noad preceding |q|}
  12176. @!r_type:small_number; {the |type| of noad |r|, or |op_noad| if |r=null|}
  12177. @!t:small_number; {the effective |type| of noad |q| during the second pass}
  12178. @!p,@!x,@!y,@!z: pointer; {temporary registers for list construction}
  12179. @!pen:integer; {a penalty to be inserted}
  12180. @!s:small_number; {the size of a noad to be deleted}
  12181. @!max_h,@!max_d:scaled; {maximum height and depth of the list translated so far}
  12182. @!delta:scaled; {offset between subscript and superscript}
  12183. begin mlist:=cur_mlist; penalties:=mlist_penalties;
  12184. style:=cur_style; {tuck global parameters away as local variables}
  12185. q:=mlist; r:=null; r_type:=op_noad; max_h:=0; max_d:=0;
  12186. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12187. while q<>null do @<Process node-or-noad |q| as much as possible in preparation
  12188.     for the second pass of |mlist_to_hlist|, then move to the next
  12189.     item in the mlist@>;
  12190. @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
  12191. @<Make a second pass over the mlist, removing all noads and inserting the
  12192.   proper spacing and penalties@>;
  12193. @ We use the fact that no character nodes appear in an mlist, hence
  12194. the field |type(q)| is always present.
  12195. @<Process node-or-noad...@>=
  12196. begin @<Do first-pass processing based on |type(q)|; |goto done_with_noad|
  12197.   if a noad has been fully processed, |goto check_dimensions| if it
  12198.   has been translated into |new_hlist(q)|, or |goto done_with_node|
  12199.   if a node has been fully processed@>;
  12200. check_dimensions: z:=hpack(new_hlist(q),natural);
  12201. if height(z)>max_h then max_h:=height(z);
  12202. if depth(z)>max_d then max_d:=depth(z);
  12203. free_node(z,box_node_size);
  12204. done_with_noad: r:=q; r_type:=type(r);
  12205. done_with_node: q:=link(q);
  12206. @ One of the things we must do on the first pass is change a |bin_noad| to
  12207. an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
  12208. The values of |r| and |r_type| make this fairly easy.
  12209. @<Do first-pass processing...@>=
  12210. reswitch: delta:=0;
  12211. case type(q) of
  12212. bin_noad: case r_type of
  12213.   bin_noad,op_noad,rel_noad,open_noad,punct_noad,left_noad:
  12214.     begin type(q):=ord_noad; goto reswitch;
  12215.     end;
  12216.   othercases do_nothing
  12217.   endcases;
  12218. rel_noad,close_noad,punct_noad,right_noad: begin@t@>@;@/
  12219.   @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
  12220.   if type(q)=right_noad then goto done_with_noad;
  12221.   end;
  12222. @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
  12223. @t\4@>@<Cases for nodes that can appear in an mlist, after which we
  12224.   |goto done_with_node|@>@;
  12225. othercases confusion("mlist1")
  12226. @:this can't happen mlist1}{\quad mlist1@>
  12227. endcases;@/
  12228. @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>
  12229. @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
  12230. if r_type=bin_noad then type(r):=ord_noad
  12231. @ @<Cases for nodes that can appear in an mlist...@>=
  12232. style_node: begin cur_style:=subtype(q);
  12233.   @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12234.   goto done_with_node;
  12235.   end;
  12236. choice_node: @<Change this node to a style node followed by the correct choice,
  12237.    then |goto done_with_node|@>;
  12238. ins_node,mark_node,adjust_node,
  12239.   whatsit_node,penalty_node,disc_node: goto done_with_node;
  12240. rule_node: begin if height(q)>max_h then max_h:=height(q);
  12241.   if depth(q)>max_d then max_d:=depth(q); goto done_with_node;
  12242.   end;
  12243. glue_node: begin @<Convert \(m)math glue to ordinary glue@>;
  12244.   goto done_with_node;
  12245.   end;
  12246. kern_node: begin math_kern(q,cur_mu); goto done_with_node;
  12247.   end;
  12248. @ @d choose_mlist(#)==begin p:=#(q); #(q):=null;@+end
  12249. @<Change this node to a style node...@>=
  12250. begin case cur_style div 2 of
  12251. 0: choose_mlist(display_mlist); {|display_style=0|}
  12252. 1: choose_mlist(text_mlist); {|text_style=2|}
  12253. 2: choose_mlist(script_mlist); {|script_style=4|}
  12254. 3: choose_mlist(script_script_mlist); {|script_script_style=6|}
  12255. end; {there are no other cases}
  12256. flush_node_list(display_mlist(q));
  12257. flush_node_list(text_mlist(q));
  12258. flush_node_list(script_mlist(q));
  12259. flush_node_list(script_script_mlist(q));@/
  12260. type(q):=style_node; subtype(q):=cur_style; width(q):=0; depth(q):=0;
  12261. if p<>null then
  12262.   begin z:=link(q); link(q):=p;
  12263.   while link(p)<>null do p:=link(p);
  12264.   link(p):=z;
  12265.   end;
  12266. goto done_with_node;
  12267. @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
  12268. pointing to |zero_glue|, with |subtype(q)=cond_math_glue|; in such a case
  12269. the node following will be eliminated if it is a glue or kern node and if the
  12270. current size is different from |text_size|. Unconditional math glue
  12271. (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
  12272. by |cur_mu|.
  12273. @!@:non_script_}{\.{\\nonscript} primitive@>
  12274. @<Convert \(m)math glue to ordinary glue@>=
  12275. if subtype(q)=mu_glue then
  12276.   begin x:=glue_ptr(q);
  12277.   y:=math_glue(x,cur_mu); delete_glue_ref(x); glue_ptr(q):=y;
  12278.   subtype(q):=normal;
  12279.   end
  12280. else if (cur_size<>text_size)and(subtype(q)=cond_math_glue) then
  12281.   begin p:=link(q);
  12282.   if p<>null then if (type(p)=glue_node)or(type(p)=kern_node) then
  12283.       begin link(q):=link(p); link(p):=null; flush_node_list(p);
  12284.       end;
  12285.   end
  12286. @ @<Cases for noads that can follow a |bin_noad|@>=
  12287. left_noad: goto done_with_noad;
  12288. fraction_noad: begin make_fraction(q); goto check_dimensions;
  12289.   end;
  12290. op_noad: begin delta:=make_op(q);
  12291.   if subtype(q)=limits then goto check_dimensions;
  12292.   end;
  12293. ord_noad: make_ord(q);
  12294. open_noad,inner_noad: do_nothing;
  12295. radical_noad: make_radical(q);
  12296. over_noad: make_over(q);
  12297. under_noad: make_under(q);
  12298. accent_noad: make_math_accent(q);
  12299. vcenter_noad: make_vcenter(q);
  12300. @ Most of the actual construction work of |mlist_to_hlist| is done
  12301. by procedures with names
  12302. like |make_fraction|, |make_radical|, etc. To illustrate
  12303. the general setup of such procedures, let's begin with a couple of
  12304. simple ones.
  12305. @<Declare math...@>=
  12306. procedure make_over(@!q:pointer);
  12307. begin info(nucleus(q)):=@|
  12308.   overbar(clean_box(nucleus(q),cramped_style(cur_style)),@|
  12309.   3*default_rule_thickness,default_rule_thickness);
  12310. math_type(nucleus(q)):=sub_box;
  12311. @ @<Declare math...@>=
  12312. procedure make_under(@!q:pointer);
  12313. var p,@!x,@!y: pointer; {temporary registers for box construction}
  12314. @!delta:scaled; {overall height plus depth}
  12315. begin x:=clean_box(nucleus(q),cur_style);
  12316. p:=new_kern(3*default_rule_thickness); link(x):=p;
  12317. link(p):=fraction_rule(default_rule_thickness);
  12318. y:=vpack(x,natural);
  12319. delta:=height(y)+depth(y)+default_rule_thickness;
  12320. height(y):=height(x); depth(y):=delta-height(y);
  12321. info(nucleus(q)):=y; math_type(nucleus(q)):=sub_box;
  12322. @ @<Declare math...@>=
  12323. procedure make_vcenter(@!q:pointer);
  12324. var v:pointer; {the box that should be centered vertically}
  12325. @!delta:scaled; {its height plus depth}
  12326. begin v:=info(nucleus(q));
  12327. if type(v)<>vlist_node then confusion("vcenter");
  12328. @:this can't happen vcenter}{\quad vcenter@>
  12329. delta:=height(v)+depth(v);
  12330. height(v):=axis_height(cur_size)+half(delta);
  12331. depth(v):=delta-height(v);
  12332. @ According to the rules in the \.{DVI} file specifications, we ensure alignment
  12333. @^square roots@>
  12334. between a square root sign and the rule above its nucleus by assuming that the
  12335. baseline of the square-root symbol is the same as the bottom of the rule. The
  12336. height of the square-root symbol will be the thickness of the rule, and the
  12337. depth of the square-root symbol should exceed or equal the height-plus-depth
  12338. of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
  12339. placed so that the actual clearance is |clr| plus half the excess.
  12340. @<Declare math...@>=
  12341. procedure make_radical(@!q:pointer);
  12342. var x,@!y:pointer; {temporary registers for box construction}
  12343. @!delta,@!clr:scaled; {dimensions involved in the calculation}
  12344. begin x:=clean_box(nucleus(q),cramped_style(cur_style));
  12345. if cur_style<text_style then {display style}
  12346.   clr:=default_rule_thickness+(abs(math_x_height(cur_size)) div 4)
  12347. else  begin clr:=default_rule_thickness; clr:=clr + (abs(clr) div 4);
  12348.   end;
  12349. y:=var_delimiter(left_delimiter(q),cur_size,height(x)+depth(x)+clr+
  12350.   default_rule_thickness);
  12351. delta:=depth(y)-(height(x)+depth(x)+clr);
  12352. if delta>0 then clr:=clr+half(delta); {increase the actual clearance}
  12353. shift_amount(y):=-(height(x)+clr);
  12354. link(y):=overbar(x,clr,height(y));
  12355. info(nucleus(q)):=hpack(y,natural); math_type(nucleus(q)):=sub_box;
  12356. @ Slants are not considered when placing accents in math mode. The accenter is
  12357. centered over the accentee, and the accent width is treated as zero with
  12358. respect to the size of the final box.
  12359. @<Declare math...@>=
  12360. procedure make_math_accent(@!q:pointer);
  12361. label done,done1;
  12362. var p,@!x,@!y:pointer; {temporary registers for box construction}
  12363. @!a:integer; {address of lig/kern instruction}
  12364. @!c:quarterword; {accent character}
  12365. @!f:internal_font_number; {its font}
  12366. @!i:four_quarters; {its |char_info|}
  12367. @!s:scaled; {amount to skew the accent to the right}
  12368. @!h:scaled; {height of character being accented}
  12369. @!delta:scaled; {space to remove between accent and accentee}
  12370. @!w:scaled; {width of the accentee, not including sub/superscripts}
  12371. begin fetch(accent_chr(q));
  12372. if char_exists(cur_i) then
  12373.   begin i:=cur_i; c:=cur_c; f:=cur_f;@/
  12374.   @<Compute the amount of skew@>;
  12375.   x:=clean_box(nucleus(q),cramped_style(cur_style)); w:=width(x); h:=height(x);
  12376.   @<Switch to a larger accent if available and appropriate@>;
  12377.   if h<x_height(f) then delta:=h@+else delta:=x_height(f);
  12378.   if (math_type(supscr(q))<>empty)or(math_type(subscr(q))<>empty) then
  12379.     if math_type(nucleus(q))=math_char then
  12380.       @<Swap the subscript and superscript into box |x|@>;
  12381.   y:=char_box(f,c);
  12382.   shift_amount(y):=s+half(w-width(y));
  12383.   width(y):=0; p:=new_kern(-delta); link(p):=x; link(y):=p;
  12384.   y:=vpack(y,natural); width(y):=width(x);
  12385.   if height(y)<h then @<Make the height of box |y| equal to |h|@>;
  12386.   info(nucleus(q)):=y;
  12387.   math_type(nucleus(q)):=sub_box;
  12388.   end;
  12389. @ @<Make the height of box |y|...@>=
  12390. begin p:=new_kern(h-height(y)); link(p):=list_ptr(y); list_ptr(y):=p;
  12391. height(y):=h;
  12392. @ @<Switch to a larger accent if available and appropriate@>=
  12393. loop@+  begin if char_tag(i)<>list_tag then goto done;
  12394.   y:=rem_byte(i);
  12395.   i:=char_info(f)(y);
  12396.   if not char_exists(i) then goto done;
  12397.   if char_width(f)(i)>w then goto done;
  12398.   c:=y;
  12399.   end;
  12400. done:
  12401. @ @<Compute the amount of skew@>=
  12402. s:=0;
  12403. if math_type(nucleus(q))=math_char then
  12404.   begin fetch(nucleus(q));
  12405.   if char_tag(cur_i)=lig_tag then
  12406.     begin a:=lig_kern_start(cur_f)(cur_i);
  12407.     cur_i:=font_info[a].qqqq;
  12408.     if skip_byte(cur_i)>stop_flag then
  12409.       begin a:=lig_kern_restart(cur_f)(cur_i);
  12410.       cur_i:=font_info[a].qqqq;
  12411.       end;
  12412.     loop@+ begin if qo(next_char(cur_i))=skew_char[cur_f] then
  12413.         begin if op_byte(cur_i)>=kern_flag then
  12414.           if skip_byte(cur_i)<=stop_flag then s:=char_kern(cur_f)(cur_i);
  12415.         goto done1;
  12416.         end;
  12417.       if skip_byte(cur_i)>=stop_flag then goto done1;
  12418.       a:=a+qo(skip_byte(cur_i))+1;
  12419.       cur_i:=font_info[a].qqqq;
  12420.       end;
  12421.     end;
  12422.   end;
  12423. done1:
  12424. @ @<Swap the subscript and superscript into box |x|@>=
  12425. begin flush_node_list(x); x:=new_noad;
  12426. mem[nucleus(x)]:=mem[nucleus(q)];
  12427. mem[supscr(x)]:=mem[supscr(q)];
  12428. mem[subscr(x)]:=mem[subscr(q)];@/
  12429. mem[supscr(q)].hh:=empty_field;
  12430. mem[subscr(q)].hh:=empty_field;@/
  12431. math_type(nucleus(q)):=sub_mlist; info(nucleus(q)):=x;
  12432. x:=clean_box(nucleus(q),cur_style); delta:=delta+height(x)-h; h:=height(x);
  12433. @ The |make_fraction| procedure is a bit different because it sets
  12434. |new_hlist(q)| directly rather than making a sub-box.
  12435. @<Declare math...@>=
  12436. procedure make_fraction(@!q:pointer);
  12437. var p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12438. @!delta,@!delta1,@!delta2,@!shift_up,@!shift_down,@!clr:scaled;
  12439.   {dimensions for box calculations}
  12440. begin if thickness(q)=default_code then thickness(q):=default_rule_thickness;
  12441. @<Create equal-width boxes |x| and |z| for the numerator and denominator,
  12442.   and compute the default amounts |shift_up| and |shift_down| by which they
  12443.   are displaced from the baseline@>;
  12444. if thickness(q)=0 then @<Adjust \(s)|shift_up| and |shift_down| for the case
  12445.   of no fraction line@>
  12446. else @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
  12447. @<Construct a vlist box for the fraction, according to |shift_up| and
  12448.   |shift_down|@>;
  12449. @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
  12450.   point to it@>;
  12451. @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
  12452. x:=clean_box(numerator(q),num_style(cur_style));
  12453. z:=clean_box(denominator(q),denom_style(cur_style));
  12454. if width(x)<width(z) then x:=rebox(x,width(z))
  12455. else z:=rebox(z,width(x));
  12456. if cur_style<text_style then {text style}
  12457.   begin shift_up:=num1(cur_size); shift_down:=denom1(cur_size);
  12458.   end
  12459. else  begin shift_down:=denom2(cur_size);
  12460.   if thickness(q)<>0 then shift_up:=num2(cur_size)
  12461.   else shift_up:=num3(cur_size);
  12462.   end
  12463. @ The numerator and denominator must be separated by a certain minimum
  12464. clearance, called |clr| in the following program. The difference between
  12465. |clr| and the actual clearance is |2delta|.
  12466. @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
  12467. begin if cur_style<text_style then clr:=7*default_rule_thickness
  12468. else clr:=3*default_rule_thickness;
  12469. delta:=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
  12470. if delta>0 then
  12471.   begin shift_up:=shift_up+delta;
  12472.   shift_down:=shift_down+delta;
  12473.   end;
  12474. @ In the case of a fraction line, the minimum clearance depends on the actual
  12475. thickness of the line.
  12476. @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
  12477. begin if cur_style<text_style then clr:=3*thickness(q)
  12478. else clr:=thickness(q);
  12479. delta:=half(thickness(q));
  12480. delta1:=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
  12481. delta2:=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
  12482. if delta1>0 then shift_up:=shift_up+delta1;
  12483. if delta2>0 then shift_down:=shift_down+delta2;
  12484. @ @<Construct a vlist box for the fraction...@>=
  12485. v:=new_null_box; type(v):=vlist_node;
  12486. height(v):=shift_up+height(x); depth(v):=depth(z)+shift_down;
  12487. width(v):=width(x); {this also equals |width(z)|}
  12488. if thickness(q)=0 then
  12489.   begin p:=new_kern((shift_up-depth(x))-(height(z)-shift_down));
  12490.   link(p):=z;
  12491.   end
  12492. else  begin y:=fraction_rule(thickness(q));@/
  12493.   p:=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
  12494.   link(y):=p; link(p):=z;@/
  12495.   p:=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
  12496.   link(p):=y;
  12497.   end;
  12498. link(x):=p; list_ptr(v):=x
  12499. @ @<Put the \(f)fraction into a box with its delimiters...@>=
  12500. if cur_style<text_style then delta:=delim1(cur_size)
  12501. else delta:=delim2(cur_size);
  12502. x:=var_delimiter(left_delimiter(q), cur_size, delta); link(x):=v;@/
  12503. z:=var_delimiter(right_delimiter(q), cur_size, delta); link(v):=z;@/
  12504. new_hlist(q):=hpack(x,natural)
  12505. @ If the nucleus of an |op_noad| is a single character, it is to be
  12506. centered vertically with respect to the axis, after first being enlarged
  12507. (via a character list in the font) if we are in display style.  The normal
  12508. convention for placing displayed limits is to put them above and below the
  12509. operator in display style.
  12510. The italic correction is removed from the character if there is a subscript
  12511. and the limits are not being displayed. The |make_op|
  12512. routine returns the value that should be used as an offset between
  12513. subscript and superscript.
  12514. After |make_op| has acted, |subtype(q)| will be |limits| if and only if
  12515. the limits have been set above and below the operator. In that case,
  12516. |new_hlist(q)| will already contain the desired final box.
  12517. @<Declare math...@>=
  12518. function make_op(@!q:pointer):scaled;
  12519. var delta:scaled; {offset between subscript and superscript}
  12520. @!p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12521. @!c:quarterword;@+@!i:four_quarters; {registers for character examination}
  12522. @!shift_up,@!shift_down:scaled; {dimensions for box calculation}
  12523. begin if (subtype(q)=normal)and(cur_style<text_style) then
  12524.   subtype(q):=limits;
  12525. if math_type(nucleus(q))=math_char then
  12526.   begin fetch(nucleus(q));
  12527.   if (cur_style<text_style)and(char_tag(cur_i)=list_tag) then {make it larger}
  12528.     begin c:=rem_byte(cur_i); i:=char_info(cur_f)(c);
  12529.     if char_exists(i) then
  12530.       begin cur_c:=c; cur_i:=i; character(nucleus(q)):=c;
  12531.       end;
  12532.     end;
  12533.   delta:=char_italic(cur_f)(cur_i); x:=clean_box(nucleus(q),cur_style);
  12534.   if (math_type(subscr(q))<>empty)and(subtype(q)<>limits) then
  12535.     width(x):=width(x)-delta; {remove italic correction}
  12536.   shift_amount(x):=half(height(x)-depth(x)) - axis_height(cur_size);
  12537.     {center vertically}
  12538.   math_type(nucleus(q)):=sub_box; info(nucleus(q)):=x;
  12539.   end
  12540. else delta:=0;
  12541. if subtype(q)=limits then
  12542.   @<Construct a box with limits above and below it, skewed by |delta|@>;
  12543. make_op:=delta;
  12544. @ The following program builds a vlist box |v| for displayed limits. The
  12545. width of the box is not affected by the fact that the limits may be skewed.
  12546. @<Construct a box with limits above and below it...@>=
  12547. begin x:=clean_box(supscr(q),sup_style(cur_style));
  12548. y:=clean_box(nucleus(q),cur_style);
  12549. z:=clean_box(subscr(q),sub_style(cur_style));
  12550. v:=new_null_box; type(v):=vlist_node; width(v):=width(y);
  12551. if width(x)>width(v) then width(v):=width(x);
  12552. if width(z)>width(v) then width(v):=width(z);
  12553. x:=rebox(x,width(v)); y:=rebox(y,width(v)); z:=rebox(z,width(v));@/
  12554. shift_amount(x):=half(delta); shift_amount(z):=-shift_amount(x);
  12555. height(v):=height(y); depth(v):=depth(y);
  12556. @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to
  12557.   account for their presence@>;
  12558. new_hlist(q):=v;
  12559. @ We use |shift_up| and |shift_down| in the following program for the
  12560. amount of glue between the displayed operator |y| and its limits |x| and
  12561. |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
  12562. by |z|, with kern nodes for the spaces between and around them.
  12563. @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
  12564. if math_type(supscr(q))=empty then
  12565.   begin free_node(x,box_node_size); list_ptr(v):=y;
  12566.   end
  12567. else  begin shift_up:=big_op_spacing3-depth(x);
  12568.   if shift_up<big_op_spacing1 then shift_up:=big_op_spacing1;
  12569.   p:=new_kern(shift_up); link(p):=y; link(x):=p;@/
  12570.   p:=new_kern(big_op_spacing5); link(p):=x; list_ptr(v):=p;
  12571.   height(v):=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
  12572.   end;
  12573. if math_type(subscr(q))=empty then free_node(z,box_node_size)
  12574. else  begin shift_down:=big_op_spacing4-height(z);
  12575.   if shift_down<big_op_spacing2 then shift_down:=big_op_spacing2;
  12576.   p:=new_kern(shift_down); link(y):=p; link(p):=z;@/
  12577.   p:=new_kern(big_op_spacing5); link(z):=p;
  12578.   depth(v):=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
  12579.   end
  12580. @ A ligature found in a math formula does not create a |ligature_node|, because
  12581. there is no question of hyphenation afterwards; the ligature will simply be
  12582. stored in an ordinary |char_node|, after residing in an |ord_noad|.
  12583. The |math_type| is converted to |math_text_char| here if we would not want to
  12584. apply an italic correction to the current character unless it belongs
  12585. to a math font (i.e., a font with |space=0|).
  12586. No boundary characters enter into these ligatures.
  12587. @<Declare math...@>=
  12588. procedure make_ord(@!q:pointer);
  12589. label restart,exit;
  12590. var a:integer; {address of lig/kern instruction}
  12591. @!p,@!r:pointer; {temporary registers for list manipulation}
  12592. begin restart:@t@>@;@/
  12593. if math_type(subscr(q))=empty then if math_type(supscr(q))=empty then
  12594.  if math_type(nucleus(q))=math_char then
  12595.   begin p:=link(q);
  12596.   if p<>null then if (type(p)>=ord_noad)and(type(p)<=punct_noad) then
  12597.     if math_type(nucleus(p))=math_char then
  12598.     if fam(nucleus(p))=fam(nucleus(q)) then
  12599.       begin math_type(nucleus(q)):=math_text_char;
  12600.       fetch(nucleus(q));
  12601.       if char_tag(cur_i)=lig_tag then
  12602.         begin a:=lig_kern_start(cur_f)(cur_i);
  12603.         cur_c:=character(nucleus(p));
  12604.         cur_i:=font_info[a].qqqq;
  12605.         if skip_byte(cur_i)>stop_flag then
  12606.           begin a:=lig_kern_restart(cur_f)(cur_i);
  12607.           cur_i:=font_info[a].qqqq;
  12608.           end;
  12609.         loop@+ begin @<If instruction |cur_i| is a kern with |cur_c|, attach
  12610.             the kern after~|q|; or if it is a ligature with |cur_c|, combine
  12611.             noads |q| and~|p| appropriately; then |return| if the cursor has
  12612.             moved past a noad, or |goto restart|@>;
  12613.           if skip_byte(cur_i)>=stop_flag then return;
  12614.           a:=a+qo(skip_byte(cur_i))+1;
  12615.           cur_i:=font_info[a].qqqq;
  12616.           end;
  12617.         end;
  12618.       end;
  12619.   end;
  12620. exit:end;
  12621. @ Note that a ligature between an |ord_noad| and another kind of noad
  12622. is replaced by an |ord_noad|, when the two noads collapse into one.
  12623. But we could make a parenthesis (say) change shape when it follows
  12624. certain letters. Presumably a font designer will define such
  12625. ligatures only when this convention makes sense.
  12626. \chardef\?='174 % vertical line to indicate character retention
  12627. @<If instruction |cur_i| is a kern with |cur_c|, ...@>=
  12628. if next_char(cur_i)=cur_c then if skip_byte(cur_i)<=stop_flag then
  12629.   if op_byte(cur_i)>=kern_flag then
  12630.     begin p:=new_kern(char_kern(cur_f)(cur_i));
  12631.     link(p):=link(q); link(q):=p; return;
  12632.     end
  12633.   else  begin check_interrupt; {allow a way out of infinite ligature loop}
  12634.     case op_byte(cur_i) of
  12635.   qi(1),qi(5): character(nucleus(q)):=rem_byte(cur_i); {\.{=:\?}, \.{=:\?>}}
  12636.   qi(2),qi(6): character(nucleus(p)):=rem_byte(cur_i); {\.{\?=:}, \.{\?=:>}}
  12637.   qi(3),qi(7),qi(11):begin r:=new_noad; {\.{\?=:\?}, \.{\?=:\?>}, \.{\?=:\?>>}}
  12638.       character(nucleus(r)):=rem_byte(cur_i);
  12639.       fam(nucleus(r)):=fam(nucleus(q));@/
  12640.       link(q):=r; link(r):=p;
  12641.       if op_byte(cur_i)<qi(11) then math_type(nucleus(r)):=math_char
  12642.       else math_type(nucleus(r)):=math_text_char; {prevent combination}
  12643.       end;
  12644.     othercases begin link(q):=link(p);
  12645.       character(nucleus(q)):=rem_byte(cur_i); {\.{=:}}
  12646.       mem[subscr(q)]:=mem[subscr(p)]; mem[supscr(q)]:=mem[supscr(p)];@/
  12647.       free_node(p,noad_size);
  12648.       end
  12649.     endcases;
  12650.     if op_byte(cur_i)>qi(3) then return;
  12651.     math_type(nucleus(q)):=math_char; goto restart;
  12652.     end
  12653. @ When we get to the following part of the program, we have ``fallen through''
  12654. from cases that did not lead to |check_dimensions| or |done_with_noad| or
  12655. |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
  12656. converted to an hlist, and whose subscripts and superscripts need to be
  12657. appended if they are present.
  12658. If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
  12659. by which a superscript should be moved right with respect to a subscript
  12660. when both are present.
  12661. @^subscripts@>
  12662. @^superscripts@>
  12663. @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
  12664. case math_type(nucleus(q)) of
  12665. math_char, math_text_char:
  12666.   @<Create a character node |p| for |nucleus(q)|, possibly followed
  12667.   by a kern node for the italic correction, and set |delta| to the
  12668.   italic correction if a subscript is present@>;
  12669. empty: p:=null;
  12670. sub_box: p:=info(nucleus(q));
  12671. sub_mlist: begin cur_mlist:=info(nucleus(q)); save_style:=cur_style;
  12672.   mlist_penalties:=false; mlist_to_hlist; {recursive call}
  12673. @^recursion@>
  12674.   cur_style:=save_style; @<Set up the values...@>;
  12675.   p:=hpack(link(temp_head),natural);
  12676.   end;
  12677. othercases confusion("mlist2")
  12678. @:this can't happen mlist2}{\quad mlist2@>
  12679. endcases;@/
  12680. new_hlist(q):=p;
  12681. if (math_type(subscr(q))=empty)and(math_type(supscr(q))=empty) then
  12682.   goto check_dimensions;
  12683. make_scripts(q,delta)
  12684. @ @<Create a character node |p| for |nucleus(q)|...@>=
  12685. begin fetch(nucleus(q));
  12686. if char_exists(cur_i) then
  12687.   begin delta:=char_italic(cur_f)(cur_i); p:=new_character(cur_f,qo(cur_c));
  12688.   if (math_type(nucleus(q))=math_text_char)and(space(cur_f)<>0) then
  12689.     delta:=0; {no italic correction in mid-word of text font}
  12690.   if (math_type(subscr(q))=empty)and(delta<>0) then
  12691.     begin link(p):=new_kern(delta); delta:=0;
  12692.     end;
  12693.   end
  12694. else p:=null;
  12695. @ The purpose of |make_scripts(q,delta)| is to attach the subscript and/or
  12696. superscript of noad |q| to the list that starts at |new_hlist(q)|,
  12697. given that subscript and superscript aren't both empty. The superscript
  12698. will appear to the right of the subscript by a given distance |delta|.
  12699. We set |shift_down| and |shift_up| to the minimum amounts to shift the
  12700. baseline of subscripts and superscripts based on the given nucleus.
  12701. @<Declare math...@>=
  12702. procedure make_scripts(@!q:pointer;@!delta:scaled);
  12703. var p,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12704. @!shift_up,@!shift_down,@!clr:scaled; {dimensions in the calculation}
  12705. @!t:small_number; {subsidiary size code}
  12706. begin p:=new_hlist(q);
  12707. if is_char_node(p) then
  12708.   begin shift_up:=0; shift_down:=0;
  12709.   end
  12710. else  begin z:=hpack(p,natural);
  12711.   if cur_style<script_style then t:=script_size@+else t:=script_script_size;
  12712.   shift_up:=height(z)-sup_drop(t);
  12713.   shift_down:=depth(z)+sub_drop(t);
  12714.   free_node(z,box_node_size);
  12715.   end;
  12716. if math_type(supscr(q))=empty then
  12717.   @<Construct a subscript box |x| when there is no superscript@>
  12718. else  begin @<Construct a superscript box |x|@>;
  12719.   if math_type(subscr(q))=empty then shift_amount(x):=-shift_up
  12720.   else @<Construct a sub/superscript combination box |x|, with the
  12721.     superscript offset by |delta|@>;
  12722.   end;
  12723. if new_hlist(q)=null then new_hlist(q):=x
  12724. else  begin p:=new_hlist(q);
  12725.   while link(p)<>null do p:=link(p);
  12726.   link(p):=x;
  12727.   end;
  12728. @ When there is a subscript without a superscript, the top of the subscript
  12729. should not exceed the baseline plus four-fifths of the x-height.
  12730. @<Construct a subscript box |x| when there is no superscript@>=
  12731. begin x:=clean_box(subscr(q),sub_style(cur_style));
  12732. width(x):=width(x)+script_space;
  12733. if shift_down<sub1(cur_size) then shift_down:=sub1(cur_size);
  12734. clr:=height(x)-(abs(math_x_height(cur_size)*4) div 5);
  12735. if shift_down<clr then shift_down:=clr;
  12736. shift_amount(x):=shift_down;
  12737. @ The bottom of a superscript should never descend below the baseline plus
  12738. one-fourth of the x-height.
  12739. @<Construct a superscript box |x|@>=
  12740. begin x:=clean_box(supscr(q),sup_style(cur_style));
  12741. width(x):=width(x)+script_space;
  12742. if odd(cur_style) then clr:=sup3(cur_size)
  12743. else if cur_style<text_style then clr:=sup1(cur_size)
  12744. else clr:=sup2(cur_size);
  12745. if shift_up<clr then shift_up:=clr;
  12746. clr:=depth(x)+(abs(math_x_height(cur_size)) div 4);
  12747. if shift_up<clr then shift_up:=clr;
  12748. @ When both subscript and superscript are present, the subscript must be
  12749. separated from the superscript by at least four times |default_rule_thickness|.
  12750. If this condition would be violated, the subscript moves down, after which
  12751. both subscript and superscript move up so that the bottom of the superscript
  12752. is at least as high as the baseline plus four-fifths of the x-height.
  12753. @<Construct a sub/superscript combination box |x|...@>=
  12754. begin y:=clean_box(subscr(q),sub_style(cur_style));
  12755. width(y):=width(y)+script_space;
  12756. if shift_down<sub2(cur_size) then shift_down:=sub2(cur_size);
  12757. clr:=4*default_rule_thickness-
  12758.   ((shift_up-depth(x))-(height(y)-shift_down));
  12759. if clr>0 then
  12760.   begin shift_down:=shift_down+clr;
  12761.   clr:=(abs(math_x_height(cur_size)*4) div 5)-(shift_up-depth(x));
  12762.   if clr>0 then
  12763.     begin shift_up:=shift_up+clr;
  12764.     shift_down:=shift_down-clr;
  12765.     end;
  12766.   end;
  12767. shift_amount(x):=delta; {superscript is |delta| to the right of the subscript}
  12768. p:=new_kern((shift_up-depth(x))-(height(y)-shift_down)); link(x):=p; link(p):=y;
  12769. x:=vpack(x,natural); shift_amount(x):=shift_down;
  12770. @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
  12771. The second pass simply goes through and hooks everything together with the
  12772. proper glue and penalties. It also handles the |left_noad| and |right_noad| that
  12773. might be present, since |max_h| and |max_d| are now known. Variable |p| points
  12774. to a node at the current end of the final hlist.
  12775. @<Make a second pass over the mlist, ...@>=
  12776. p:=temp_head; link(p):=null; q:=mlist; r_type:=0; cur_style:=style;
  12777. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12778. while q<>null do
  12779.   begin @<If node |q| is a style node, change the style and |goto delete_q|;
  12780.     otherwise if it is not a noad, put it into the hlist,
  12781.     advance |q|, and |goto done|; otherwise set |s| to the size
  12782.     of noad |q|, set |t| to the associated type (|ord_noad..
  12783.     inner_noad|), and set |pen| to the associated penalty@>;
  12784.   @<Append inter-element spacing based on |r_type| and |t|@>;
  12785.   @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
  12786.   r_type:=t;
  12787.   delete_q: r:=q; q:=link(q); free_node(r,s);
  12788.   done: end
  12789. @ Just before doing the big |case| switch in the second pass, the program
  12790. sets up default values so that most of the branches are short.
  12791. @<If node |q| is a style node, change the style...@>=
  12792. t:=ord_noad; s:=noad_size; pen:=inf_penalty;
  12793. case type(q) of
  12794. op_noad,open_noad,close_noad,punct_noad,inner_noad: t:=type(q);
  12795. bin_noad: begin t:=bin_noad; pen:=bin_op_penalty;
  12796.   end;
  12797. rel_noad: begin t:=rel_noad; pen:=rel_penalty;
  12798.   end;
  12799. ord_noad,vcenter_noad,over_noad,under_noad: do_nothing;
  12800. radical_noad: s:=radical_noad_size;
  12801. accent_noad: s:=accent_noad_size;
  12802. fraction_noad: begin t:=inner_noad; s:=fraction_noad_size;
  12803.   end;
  12804. left_noad,right_noad: t:=make_left_right(q,style,max_d,max_h);
  12805. style_node: @<Change the current style and |goto delete_q|@>;
  12806. whatsit_node,penalty_node,rule_node,disc_node,adjust_node,ins_node,mark_node,
  12807.  glue_node,kern_node:@t@>@;@/
  12808.   begin link(p):=q; p:=q; q:=link(q); link(p):=null; goto done;
  12809.   end;
  12810. othercases confusion("mlist3")
  12811. @:this can't happen mlist3}{\quad mlist3@>
  12812. endcases
  12813. @ The |make_left_right| function constructs a left or right delimiter of
  12814. the required size and returns the value |open_noad| or |close_noad|. The
  12815. |right_noad| and |left_noad| will both be based on the original |style|,
  12816. so they will have consistent sizes.
  12817. We use the fact that |right_noad-left_noad=close_noad-open_noad|.
  12818. @<Declare math...@>=
  12819. function make_left_right(@!q:pointer;@!style:small_number;
  12820.   @!max_d,@!max_h:scaled):small_number;
  12821. var delta,@!delta1,@!delta2:scaled; {dimensions used in the calculation}
  12822. begin if style<script_style then cur_size:=text_size
  12823. else cur_size:=16*((style-text_style) div 2);
  12824. delta2:=max_d+axis_height(cur_size);
  12825. delta1:=max_h+max_d-delta2;
  12826. if delta2>delta1 then delta1:=delta2; {|delta1| is max distance from axis}
  12827. delta:=(delta1 div 500)*delimiter_factor;
  12828. delta2:=delta1+delta1-delimiter_shortfall;
  12829. if delta<delta2 then delta:=delta2;
  12830. new_hlist(q):=var_delimiter(delimiter(q),cur_size,delta);
  12831. make_left_right:=type(q)-(left_noad-open_noad); {|open_noad| or |close_noad|}
  12832. @ @<Change the current style and |goto delete_q|@>=
  12833. begin cur_style:=subtype(q); s:=style_node_size;
  12834. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12835. goto delete_q;
  12836. @ The inter-element spacing in math formulas depends on a $8\times8$ table that
  12837. \TeX\ preloads as a 64-digit string. The elements of this string have the
  12838. following significance:
  12839. $$\vbox{\halign{#\hfil\cr
  12840. \.0 means no space;\cr
  12841. \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
  12842. \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
  12843. \.3 means a conditional medium space
  12844.   (\.{\\nonscript\\mskip\\medmuskip});\cr
  12845. \.4 means a conditional thick space
  12846.   (\.{\\nonscript\\mskip\\thickmuskip});\cr
  12847. \.* means an impossible case.\cr}}$$
  12848. This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
  12849. supposed to happen, and the string makes it happen.
  12850. @:TeXbook}{\sl The \TeX book@>
  12851. A global variable |magic_offset| is computed so that if |a| and |b| are
  12852. in the range |ord_noad..inner_noad|, then |str_pool[a*8+b+magic_offset]|
  12853. is the digit for spacing between noad types |a| and |b|.
  12854. If \PASCAL\ had provided a good way to preload constant arrays, this part of
  12855. the program would not have been so strange.
  12856. @:PASCAL}{\PASCAL@>
  12857. @d math_spacing=@;@/
  12858. @t\hskip-35pt@>
  12859. "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
  12860. @t$ \hskip-35pt$@>
  12861. @<Glob...@>=
  12862. @!magic_offset:integer; {used to find inter-element spacing}
  12863. @ @<Compute the magic offset@>=
  12864. magic_offset:=str_start[math_spacing]-9*ord_noad
  12865. @ @<Append inter-element spacing based on |r_type| and |t|@>=
  12866. if r_type>0 then {not the first noad}
  12867.   begin case so(str_pool[r_type*8+t+magic_offset]) of
  12868.   "0": x:=0;
  12869.   "1": if cur_style<script_style then x:=thin_mu_skip_code@+else x:=0;
  12870.   "2": x:=thin_mu_skip_code;
  12871.   "3": if cur_style<script_style then x:=med_mu_skip_code@+else x:=0;
  12872.   "4": if cur_style<script_style then x:=thick_mu_skip_code@+else x:=0;
  12873.   othercases confusion("mlist4")
  12874. @:this can't happen mlist4}{\quad mlist4@>
  12875.   endcases;
  12876.   if x<>0 then
  12877.     begin y:=math_glue(glue_par(x),cur_mu);
  12878.     z:=new_glue(y); glue_ref_count(y):=null; link(p):=z; p:=z;@/
  12879.     subtype(z):=x+1; {store a symbolic subtype}
  12880.     end;
  12881.   end
  12882. @ We insert a penalty node after the hlist entries of noad |q| if |pen|
  12883. is not an ``infinite'' penalty, and if the node immediately following |q|
  12884. is not a penalty node or a |rel_noad| or absent entirely.
  12885. @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
  12886. if new_hlist(q)<>null then
  12887.   begin link(p):=new_hlist(q);
  12888.   repeat p:=link(p);
  12889.   until link(p)=null;
  12890.   end;
  12891. if penalties then if link(q)<>null then if pen<inf_penalty then
  12892.   begin r_type:=type(link(q));
  12893.   if r_type<>penalty_node then if r_type<>rel_noad then
  12894.     begin z:=new_penalty(pen); link(p):=z; p:=z;
  12895.     end;
  12896.   end
  12897. @* \[37] Alignment.
  12898. It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
  12899. they cut across so many of the control structures of \TeX.
  12900. Therefore the
  12901. present page is probably not the best place for a beginner to start reading
  12902. this program; it is better to master everything else first.
  12903. Let us focus our thoughts on an example of what the input might be, in order
  12904. to get some idea about how the alignment miracle happens. The example doesn't
  12905. do anything useful, but it is sufficiently general to indicate all of the
  12906. special cases that must be dealt with; please do not be disturbed by its
  12907. apparent complexity and meaninglessness.
  12908. $$\vbox{\halign{\.{#}\hfil\cr
  12909. {}\\tabskip 2pt plus 3pt\cr
  12910. {}\\halign to 300pt\{u1\#v1\&\cr
  12911. \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
  12912. \hskip 50pt u3\#v3\\cr\cr
  12913. \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
  12914. \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
  12915. \hskip 25pt b1\\span b2\\cr\cr
  12916. \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
  12917. Here's what happens:
  12918. \yskip
  12919. (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
  12920. places the 300pt dimension onto the |save_stack|, and an |align_group|
  12921. code is placed above it. This will make it possible to complete the alignment
  12922. when the matching `\.\}' is found.
  12923. (1) The preamble is scanned next. Macros in the preamble are not expanded,
  12924. @^preamble@>
  12925. except as part of a tabskip specification. For example, if \.{u2} had been
  12926. a macro in the preamble above, it would have been expanded, since \TeX\
  12927. must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
  12928. is constructed based on the user's preamble; in our case it contains the
  12929. following seven items:
  12930. $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
  12931. {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
  12932. {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
  12933. {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
  12934. {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
  12935. {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
  12936. {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
  12937. {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
  12938. These ``alignrecord'' entries have the same size as an |unset_node|,
  12939. since they will later be converted into such nodes. However, at the
  12940. moment they have no |type| or |subtype| fields; they have |info| fields
  12941. instead, and these |info| fields are initially set to the value |end_span|,
  12942. for reasons explained below. Furthermore, the alignrecord nodes have no
  12943. |height| or |depth| fields; these are renamed |u_part| and |v_part|,
  12944. and they point to token lists for the templates of the alignment.
  12945. For example, the |u_part| field in the first alignrecord points to the
  12946. token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
  12947. (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
  12948. It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
  12949. be read again, and the template `\.{u1}' is fed to the scanner. Just
  12950. before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
  12951. Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
  12952. {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
  12953. token, indicating the end of a column. At this point an |unset_node| is
  12954. created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
  12955. The natural width of this unset node replaces the |width| field of the
  12956. alignrecord for column~1; in general, the alignrecords will record the
  12957. maximum natural width that has occurred so far in a given column.
  12958. (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
  12959. are now bypassed. Again \TeX\ goes into restricted horizontal mode and
  12960. makes an |unset_node| from the resulting hlist; but this time the
  12961. hlist contains simply `\.{a2}'. The natural width of the new unset box
  12962. is remembered in the |width| field of the alignrecord for column~2.
  12963. (4) A third |unset_node| is created for column 3, using essentially the
  12964. mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
  12965. v3}'. The vertical rule in this case has running dimensions that will later
  12966. extend to the height and depth of the whole first row, since each |unset_node|
  12967. in a row will eventually inherit the height and depth of its enclosing box.
  12968. (5) The first row has now ended; it is made into a single unset box
  12969. comprising the following seven items:
  12970. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12971. {}\\glue 2pt plus 3pt\cr
  12972. {}\\unsetbox for 1 column: u1a1v1\cr
  12973. {}\\glue 2pt plus 3pt\cr
  12974. {}\\unsetbox for 1 column: a2\cr
  12975. {}\\glue 1pt plus 1fil\cr
  12976. {}\\unsetbox for 1 column: u3\\vrule v3\cr
  12977. {}\\glue 1pt plus 1fil\cr}}$$
  12978. The width of this unset row is unimportant, but it has the correct height
  12979. and depth, so the correct baselineskip glue will be computed as the row
  12980. is inserted into a vertical list.
  12981. (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
  12982. additional material (in this case \.{\\vskip 3pt}) to the vertical list.
  12983. While processing this material, \TeX\ will be in internal vertical
  12984. mode, and |no_align_group| will be on |save_stack|.
  12985. (7) The next row produces an unset box that looks like this:
  12986. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12987. {}\\glue 2pt plus 3pt\cr
  12988. {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
  12989. {}\\glue 1pt plus 1fil\cr
  12990. {}\\unsetbox for 1 column: {\rm(empty)}\cr
  12991. {}\\glue 1pt plus 1fil\cr}}$$
  12992. The natural width of the unset box that spans columns 1~and~2 is stored
  12993. in a ``span node,'' which we will explain later; the |info| field of the
  12994. alignrecord for column~1 now points to the new span node, and the |info|
  12995. of the span node points to |end_span|.
  12996. (8) The final row produces the unset box
  12997. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12998. {}\\glue 2pt plus 3pt\cr
  12999. {}\\unsetbox for 1 column: {\rm(empty)}\cr
  13000. {}\\glue 2pt plus 3pt\cr
  13001. {}\\unsetbox for 2 columns: u2c2v2\cr
  13002. {}\\glue 1pt plus 1fil\cr}}$$
  13003. A new span node is attached to the alignrecord for column 2.
  13004. (9) The last step is to compute the true column widths and to change all the
  13005. unset boxes to hboxes, appending the whole works to the vertical list that
  13006. encloses the \.{\\halign}. The rules for deciding on the final widths of
  13007. each unset column box will be explained below.
  13008. \yskip\noindent
  13009. Note that as \.{\\halign} is being processed, we fearlessly give up control
  13010. to the rest of \TeX. At critical junctures, an alignment routine is
  13011. called upon to step in and do some little action, but most of the time
  13012. these routines just lurk in the background. It's something like
  13013. post-hypnotic suggestion.
  13014. @ We have mentioned that alignrecords contain no |height| or |depth| fields.
  13015. Their |glue_sign| and |glue_order| are pre-empted as well, since it
  13016. is necessary to store information about what to do when a template ends.
  13017. This information is called the |extra_info| field.
  13018. @d u_part(#)==mem[#+height_offset].int {pointer to \<u_j> token list}
  13019. @d v_part(#)==mem[#+depth_offset].int {pointer to \<v_j> token list}
  13020. @d extra_info(#)==info(#+list_offset) {info to remember during template}
  13021. @ Alignments can occur within alignments, so a small stack is used to access
  13022. the alignrecord information. At each level we have a |preamble| pointer,
  13023. indicating the beginning of the preamble list; a |cur_align| pointer,
  13024. indicating the current position in the preamble list; a |cur_span| pointer,
  13025. indicating the value of |cur_align| at the beginning of a sequence of
  13026. spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
  13027. an alignrecord that should be copied next if the current list is extended;
  13028. and the |align_state| variable, which indicates the nesting of braces so
  13029. that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
  13030. There also are pointers |cur_head| and |cur_tail| to the head and tail
  13031. of a list of adjustments being moved out from horizontal mode to
  13032. vertical~mode.
  13033. The current values of these seven quantities appear in global variables;
  13034. when they have to be pushed down, they are stored in 5-word nodes, and
  13035. |align_ptr| points to the topmost such node.
  13036. @d preamble==link(align_head) {the current preamble list}
  13037. @d align_stack_node_size=5 {number of |mem| words to save alignment states}
  13038. @<Glob...@>=
  13039. @!cur_align:pointer; {current position in preamble list}
  13040. @!cur_span:pointer; {start of currently spanned columns in preamble list}
  13041. @!cur_loop:pointer; {place to copy when extending a periodic preamble}
  13042. @!align_ptr:pointer; {most recently pushed-down alignment stack node}
  13043. @!cur_head,@!cur_tail:pointer; {adjustment list pointers}
  13044. @ The |align_state| and |preamble| variables are initialized elsewhere.
  13045. @<Set init...@>=
  13046. align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null;
  13047. cur_head:=null; cur_tail:=null;
  13048. @ Alignment stack maintenance is handled by a pair of trivial routines
  13049. called |push_alignment| and |pop_alignment|.
  13050. @p procedure push_alignment;
  13051. var p:pointer; {the new alignment stack node}
  13052. begin p:=get_node(align_stack_node_size);
  13053. link(p):=align_ptr; info(p):=cur_align;
  13054. llink(p):=preamble; rlink(p):=cur_span;
  13055. mem[p+2].int:=cur_loop; mem[p+3].int:=align_state;
  13056. info(p+4):=cur_head; link(p+4):=cur_tail;
  13057. align_ptr:=p;
  13058. cur_head:=get_avail;
  13059. procedure pop_alignment;
  13060. var p:pointer; {the top alignment stack node}
  13061. begin free_avail(cur_head);
  13062. p:=align_ptr;
  13063. cur_tail:=link(p+4); cur_head:=info(p+4);
  13064. align_state:=mem[p+3].int; cur_loop:=mem[p+2].int;
  13065. cur_span:=rlink(p); preamble:=llink(p);
  13066. cur_align:=info(p); align_ptr:=link(p);
  13067. free_node(p,align_stack_node_size);
  13068. @ \TeX\ has eight procedures that govern alignments: |init_align| and
  13069. |fin_align| are used at the very beginning and the very end; |init_row| and
  13070. |fin_row| are used at the beginning and end of individual rows; |init_span|
  13071. is used at the beginning of a sequence of spanned columns (possibly involving
  13072. only one column); |init_col| and |fin_col| are used at the beginning and
  13073. end of individual columns; and |align_peek| is used after \.{\\cr} to see
  13074. whether the next item is \.{\\noalign}.
  13075. We shall consider these routines in the order they are first used during
  13076. the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
  13077. |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
  13078. @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
  13079. mode, \TeX\ calls |init_align|, whose task is to get everything off to a
  13080. good start. This mostly involves scanning the preamble and putting its
  13081. information into the preamble list.
  13082. @^preamble@>
  13083. @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
  13084. procedure@?align_peek; forward;@t\2@>@/
  13085. procedure@?normal_paragraph; forward;@t\2@>@/
  13086. procedure init_align;
  13087. label done, done1, done2, continue;
  13088. var save_cs_ptr:pointer; {|warning_index| value for error messages}
  13089. @!p:pointer; {for short-term temporary use}
  13090. begin save_cs_ptr:=cur_cs; {\.{\\halign} or \.{\\valign}, usually}
  13091. push_alignment; align_state:=-1000000; {enter a new alignment level}
  13092. @<Check for improper alignment in displayed math@>;
  13093. push_nest; {enter a new semantic level}
  13094. @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
  13095. scan_spec(align_group,false);@/
  13096. @<Scan the preamble and record it in the |preamble| list@>;
  13097. new_save_level(align_group);
  13098. if every_cr<>null then begin_token_list(every_cr,every_cr_text);
  13099. align_peek; {look for \.{\\noalign} or \.{\\omit}}
  13100. @ In vertical modes, |prev_depth| already has the correct value. But
  13101. if we are in |mmode| (displayed formula mode), we reach out to the
  13102. enclosing vertical mode for the |prev_depth| value that produces the
  13103. correct baseline calculations.
  13104. @<Change current mode...@>=
  13105. if mode=mmode then
  13106.   begin mode:=-vmode; prev_depth:=nest[nest_ptr-2].aux_field.sc;
  13107.   end
  13108. else if mode>0 then negate(mode)
  13109. @ When \.{\\halign} is used as a displayed formula, there should be
  13110. no other pieces of mlists present.
  13111. @<Check for improper alignment in displayed math@>=
  13112. if (mode=mmode)and((tail<>head)or(incompleat_noad<>null)) then
  13113.   begin print_err("Improper "); print_esc("halign"); print(" inside $$'s");
  13114. @.Improper \\halign...@>
  13115.   help3("Displays can use special alignments (like \eqalignno)")@/
  13116.   ("only if nothing but the alignment itself is between $$'s.")@/
  13117.   ("So I've deleted the formulas that preceded this alignment.");
  13118.   error; flush_math;
  13119.   end
  13120. @ @<Scan the preamble and record it in the |preamble| list@>=
  13121. preamble:=null; cur_align:=align_head; cur_loop:=null; scanner_status:=aligning;
  13122. warning_index:=save_cs_ptr; align_state:=-1000000;
  13123.   {at this point, |cur_cmd=left_brace|}
  13124. loop@+  begin @<Append the current tabskip glue to the preamble list@>;
  13125.   if cur_cmd=car_ret then goto done; {\.{\\cr} ends the preamble}
  13126.   @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|,
  13127.     looking for changes in the tabskip glue; append an
  13128.     alignrecord to the preamble list@>;
  13129.   end;
  13130. done: scanner_status:=normal
  13131. @ @<Append the current tabskip glue to the preamble list@>=
  13132. link(cur_align):=new_param_glue(tab_skip_code);
  13133. cur_align:=link(cur_align)
  13134. @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
  13135. @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
  13136. link(cur_align):=new_null_box; cur_align:=link(cur_align); {a new alignrecord}
  13137. info(cur_align):=end_span; width(cur_align):=null_flag;
  13138. u_part(cur_align):=link(hold_head);
  13139. @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
  13140. v_part(cur_align):=link(hold_head)
  13141. @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
  13142. and with |span_code| as the command modifier. This makes \TeX\ interpret it
  13143. essentially the same as an alignment delimiter like `\.\&', yet it is
  13144. recognizably different when we need to distinguish it from a normal delimiter.
  13145. It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
  13146. and an even larger |cr_cr_code| to `\.{\\crcr}'.
  13147. The end of a template is represented by two ``frozen'' control sequences
  13148. called \.{\\endtemplate}. The first has the command code |end_template|, which
  13149. is |>outer_call|, so it will not easily disappear in the presence of errors.
  13150. The |get_x_token| routine converts the first into the second, which has |endv|
  13151. as its command code.
  13152. @d span_code=256 {distinct from any character}
  13153. @d cr_code=257 {distinct from |span_code| and from any character}
  13154. @d cr_cr_code=cr_code+1 {this distinguishes \.{\\crcr} from \.{\\cr}}
  13155. @d end_template_token==cs_token_flag+frozen_end_template
  13156. @<Put each of \TeX's primitives into the hash table@>=
  13157. primitive("span",tab_mark,span_code);@/
  13158. @!@:span_}{\.{\\span} primitive@>
  13159. primitive("cr",car_ret,cr_code);
  13160. @!@:cr_}{\.{\\cr} primitive@>
  13161. text(frozen_cr):="cr"; eqtb[frozen_cr]:=eqtb[cur_val];@/
  13162. primitive("crcr",car_ret,cr_cr_code);
  13163. @!@:cr_cr_}{\.{\\crcr} primitive@>
  13164. text(frozen_end_template):="endtemplate"; text(frozen_endv):="endtemplate";
  13165. eq_type(frozen_endv):=endv; equiv(frozen_endv):=null_list;
  13166. eq_level(frozen_endv):=level_one;@/
  13167. eqtb[frozen_end_template]:=eqtb[frozen_endv];
  13168. eq_type(frozen_end_template):=end_template;
  13169. @ @<Cases of |print_cmd_chr|...@>=
  13170. tab_mark: if chr_code=span_code then print_esc("span")
  13171.   else chr_cmd("alignment tab character ");
  13172. car_ret: if chr_code=cr_code then print_esc("cr")
  13173.   else print_esc("crcr");
  13174. @ The preamble is copied directly, except that \.{\\tabskip} causes a change
  13175. to the tabskip glue, thereby possibly expanding macros that immediately
  13176. follow it. An appearance of \.{\\span} also causes such an expansion.
  13177. Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
  13178. token survives in the preamble and the `\.{\\tabskip}' defines new
  13179. tabskip glue (locally).
  13180. @<Declare the procedure called |get_preamble_token|@>=
  13181. procedure get_preamble_token;
  13182. label restart;
  13183. begin restart: get_token;
  13184. while (cur_chr=span_code)and(cur_cmd=tab_mark) do
  13185.   begin get_token; {this token will be expanded once}
  13186.   if cur_cmd>max_command then
  13187.     begin expand; get_token;
  13188.     end;
  13189.   end;
  13190. if cur_cmd=endv then
  13191.   fatal_error("(interwoven alignment preambles are not allowed)");
  13192. @.interwoven alignment preambles...@>
  13193. if (cur_cmd=assign_glue)and(cur_chr=glue_base+tab_skip_code) then
  13194.   begin scan_optional_equals; scan_glue(glue_val);
  13195.   if global_defs>0 then geq_define(glue_base+tab_skip_code,glue_ref,cur_val)
  13196.   else eq_define(glue_base+tab_skip_code,glue_ref,cur_val);
  13197.   goto restart;
  13198.   end;
  13199. @ Spaces are eliminated from the beginning of a template.
  13200. @<Scan the template \<u_j>...@>=
  13201. p:=hold_head; link(p):=null;
  13202. loop@+  begin get_preamble_token;
  13203.   if cur_cmd=mac_param then goto done1;
  13204.   if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
  13205.    if (p=hold_head)and(cur_loop=null)and(cur_cmd=tab_mark)
  13206.     then cur_loop:=cur_align
  13207.    else  begin print_err("Missing # inserted in alignment preamble");
  13208. @.Missing \# inserted...@>
  13209.     help3("There should be exactly one # between &'s, when an")@/
  13210.     ("\halign or \valign is being set up. In this case you had")@/
  13211.     ("none, so I've put one in; maybe that will work.");
  13212.     back_error; goto done1;
  13213.     end
  13214.   else if (cur_cmd<>spacer)or(p<>hold_head) then
  13215.     begin link(p):=get_avail; p:=link(p); info(p):=cur_tok;
  13216.     end;
  13217.   end;
  13218. done1:
  13219. @ @<Scan the template \<v_j>...@>=
  13220. p:=hold_head; link(p):=null;
  13221. loop@+  begin continue: get_preamble_token;
  13222.   if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
  13223.     goto done2;
  13224.   if cur_cmd=mac_param then
  13225.     begin print_err("Only one # is allowed per tab");
  13226. @.Only one \# is allowed...@>
  13227.     help3("There should be exactly one # between &'s, when an")@/
  13228.     ("\halign or \valign is being set up. In this case you had")@/
  13229.     ("more than one, so I'm ignoring all but the first.");
  13230.     error; goto continue;
  13231.     end;
  13232.   link(p):=get_avail; p:=link(p); info(p):=cur_tok;
  13233.   end;
  13234. done2: link(p):=get_avail; p:=link(p);
  13235. info(p):=end_template_token {put \.{\\endtemplate} at the end}
  13236. @ The tricky part about alignments is getting the templates into the
  13237. scanner at the right time, and recovering control when a row or column
  13238. is finished.
  13239. We usually begin a row after each \.{\\cr} has been sensed, unless that
  13240. \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
  13241. the alignment. The |align_peek| routine is used to look ahead and do
  13242. the right thing; it either gets a new row started, or gets a \.{\\noalign}
  13243. started, or finishes off the alignment.
  13244. @<Declare the procedure called |align_peek|@>=
  13245. procedure align_peek;
  13246. label restart;
  13247. begin restart: align_state:=1000000; @<Get the next non-blank non-call token@>;
  13248. if cur_cmd=no_align then
  13249.   begin scan_left_brace; new_save_level(no_align_group);
  13250.   if mode=-vmode then normal_paragraph;
  13251.   end
  13252. else if cur_cmd=right_brace then fin_align
  13253. else if (cur_cmd=car_ret)and(cur_chr=cr_cr_code) then
  13254.   goto restart {ignore \.{\\crcr}}
  13255. else  begin init_row; {start a new row}
  13256.   init_col; {start a new column and replace what we peeked at}
  13257.   end;
  13258. @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
  13259. we enter a new semantic level, copy the first tabskip glue, and change
  13260. from internal vertical mode to restricted horizontal mode or vice versa.
  13261. The |space_factor| and |prev_depth| are not used on this semantic level,
  13262. but we clear them to zero just to be tidy.
  13263. @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
  13264. procedure init_row;
  13265. begin push_nest; mode:=(-hmode-vmode)-mode;
  13266. if mode=-hmode then space_factor:=0 @+else prev_depth:=0;
  13267. tail_append(new_glue(glue_ptr(preamble)));
  13268. subtype(tail):=tab_skip_code+1;@/
  13269. cur_align:=link(preamble); cur_tail:=cur_head; init_span(cur_align);
  13270. @ The parameter to |init_span| is a pointer to the alignrecord where the
  13271. next column or group of columns will begin. A new semantic level is
  13272. entered, so that the columns will generate a list for subsequent packaging.
  13273. @<Declare the procedure called |init_span|@>=
  13274. procedure init_span(@!p:pointer);
  13275. begin push_nest;
  13276. if mode=-hmode then space_factor:=1000
  13277. else  begin prev_depth:=ignore_depth; normal_paragraph;
  13278.   end;
  13279. cur_span:=p;
  13280. @ When a column begins, we assume that |cur_cmd| is either |omit| or else
  13281. the current token should be put back into the input until the \<u_j>
  13282. template has been scanned.  (Note that |cur_cmd| might be |tab_mark| or
  13283. |car_ret|.)  We also assume that |align_state| is approximately 1000000 at
  13284. this time.  We remain in the same mode, and start the template if it is
  13285. called for.
  13286. @p procedure init_col;
  13287. begin extra_info(cur_align):=cur_cmd;
  13288. if cur_cmd=omit then align_state:=0
  13289. else  begin back_input; begin_token_list(u_part(cur_align),u_template);
  13290.   end; {now |align_state=1000000|}
  13291. @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
  13292. a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state=0|,
  13293. the scanner activates the following code, which fires up the \<v_j> template.
  13294. We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
  13295. |span_code|, or a character code, depending on how the column text has ended.
  13296. This part of the program had better not be activated when the preamble
  13297. to another alignment is being scanned.
  13298. @<Insert the \(v)\<v_j>...@>=
  13299. begin if scanner_status=aligning then
  13300.   fatal_error("(interwoven alignment preambles are not allowed)");
  13301. @.interwoven alignment preambles...@>
  13302. cur_cmd:=extra_info(cur_align); extra_info(cur_align):=cur_chr;
  13303. if cur_cmd=omit then begin_token_list(omit_template,v_template)
  13304. else begin_token_list(v_part(cur_align),v_template);
  13305. align_state:=1000000; goto restart;
  13306. @ The token list |omit_template| just referred to is a constant token
  13307. list that contains the special control sequence \.{\\endtemplate} only.
  13308. @<Initialize the special...@>=
  13309. info(omit_template):=end_template_token; {|link(omit_template)=null|}
  13310. @ When the |endv| command at the end of a \<v_j> template comes through the
  13311. scanner, things really start to happen; and it is the |fin_col| routine
  13312. that makes them happen. This routine returns |true| if a row as well as a
  13313. column has been finished.
  13314. @p function fin_col:boolean;
  13315. label exit;
  13316. var p:pointer; {the alignrecord after the current one}
  13317. @!q,@!r:pointer; {temporary pointers for list manipulation}
  13318. @!s:pointer; {a new span node}
  13319. @!u:pointer; {a new unset box}
  13320. @!w:scaled; {natural width}
  13321. @!o:glue_ord; {order of infinity}
  13322. @!n:halfword; {span counter}
  13323. begin if cur_align=null then confusion("endv");
  13324. q:=link(cur_align);@+if q=null then confusion("endv");
  13325. @:this can't happen endv}{\quad endv@>
  13326. if align_state<500000 then
  13327.   fatal_error("(interwoven alignment preambles are not allowed)");
  13328. @.interwoven alignment preambles...@>
  13329. p:=link(q);
  13330. @<If the preamble list has been traversed, check that the row has ended@>;
  13331. if extra_info(cur_align)<>span_code then
  13332.   begin unsave; new_save_level(align_group);@/
  13333.   @<Package an unset box for the current column and record its width@>;
  13334.   @<Copy the tabskip glue between columns@>;
  13335.   if extra_info(cur_align)>=cr_code then
  13336.     begin fin_col:=true; return;
  13337.     end;
  13338.   init_span(p);
  13339.   end;
  13340. align_state:=1000000; @<Get the next non-blank non-call token@>;
  13341. cur_align:=p;
  13342. init_col; fin_col:=false;
  13343. exit: end;
  13344. @ @<If the preamble list has been traversed, check that the row has ended@>=
  13345. if (p=null)and(extra_info(cur_align)<cr_code) then
  13346.  if cur_loop<>null then @<Lengthen the preamble periodically@>
  13347.  else  begin print_err("Extra alignment tab has been changed to ");
  13348. @.Extra alignment tab...@>
  13349.   print_esc("cr");
  13350.   help3("You have given more \span or & marks than there were")@/
  13351.   ("in the preamble to the \halign or \valign now in progress.")@/
  13352.   ("So I'll assume that you meant to type \cr instead.");
  13353.   extra_info(cur_align):=cr_code; error;
  13354.   end
  13355. @ @<Lengthen the preamble...@>=
  13356. begin link(q):=new_null_box; p:=link(q); {a new alignrecord}
  13357. info(p):=end_span; width(p):=null_flag; cur_loop:=link(cur_loop);
  13358. @<Copy the templates from node |cur_loop| into node |p|@>;
  13359. cur_loop:=link(cur_loop);
  13360. link(p):=new_glue(glue_ptr(cur_loop));
  13361. @ @<Copy the templates from node |cur_loop| into node |p|@>=
  13362. q:=hold_head; r:=u_part(cur_loop);
  13363. while r<>null do
  13364.   begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
  13365.   end;
  13366. link(q):=null; u_part(p):=link(hold_head);
  13367. q:=hold_head; r:=v_part(cur_loop);
  13368. while r<>null do
  13369.   begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
  13370.   end;
  13371. link(q):=null; v_part(p):=link(hold_head)
  13372. @ @<Copy the tabskip glue...@>=
  13373. tail_append(new_glue(glue_ptr(link(cur_align))));
  13374. subtype(tail):=tab_skip_code+1
  13375. @ @<Package an unset...@>=
  13376. begin if mode=-hmode then
  13377.   begin adjust_tail:=cur_tail; u:=hpack(link(head),natural); w:=width(u);
  13378.   cur_tail:=adjust_tail; adjust_tail:=null;
  13379.   end
  13380. else  begin u:=vpackage(link(head),natural,0); w:=height(u);
  13381.   end;
  13382. n:=min_quarterword; {this represents a span count of 1}
  13383. if cur_span<>cur_align then @<Update width entry for spanned columns@>
  13384. else if w>width(cur_align) then width(cur_align):=w;
  13385. type(u):=unset_node; span_count(u):=n;@/
  13386. @<Determine the stretch order@>;
  13387. glue_order(u):=o; glue_stretch(u):=total_stretch[o];@/
  13388. @<Determine the shrink order@>;
  13389. glue_sign(u):=o; glue_shrink(u):=total_shrink[o];@/
  13390. pop_nest; link(tail):=u; tail:=u;
  13391. @ A span node is a 2-word record containing |width|, |info|, and |link|
  13392. fields. The |link| field is not really a link, it indicates the number of
  13393. spanned columns; the |info| field points to a span node for the same
  13394. starting column, having a greater extent of spanning, or to |end_span|,
  13395. which has the largest possible |link| field; the |width| field holds the
  13396. largest natural width corresponding to a particular set of spanned columns.
  13397. A list of the maximum widths so far, for spanned columns starting at a
  13398. given column, begins with the |info| field of the alignrecord for that
  13399. column.
  13400. @d span_node_size=2 {number of |mem| words for a span node}
  13401. @<Initialize the special list heads...@>=
  13402. link(end_span):=max_quarterword+1; info(end_span):=null;
  13403. @ @<Update width entry for spanned columns@>=
  13404. begin q:=cur_span;
  13405. repeat incr(n); q:=link(link(q));
  13406. until q=cur_align;
  13407. if n>max_quarterword then confusion("256 spans"); {this can happen, but won't}
  13408. @^system dependencies@>
  13409. @:this can't happen 256 spans}{\quad 256 spans@>
  13410. q:=cur_span; while link(info(q))<n do q:=info(q);
  13411. if link(info(q))>n then
  13412.   begin s:=get_node(span_node_size); info(s):=info(q); link(s):=n;
  13413.   info(q):=s; width(s):=w;
  13414.   end
  13415. else if width(info(q))<w then width(info(q)):=w;
  13416. @ At the end of a row, we append an unset box to the current vlist (for
  13417. \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
  13418. contains the unset boxes for the columns, separated by the tabskip glue.
  13419. Everything will be set later.
  13420. @p procedure fin_row;
  13421. var p:pointer; {the new unset box}
  13422. begin if mode=-hmode then
  13423.   begin p:=hpack(link(head),natural);
  13424.   pop_nest; append_to_vlist(p);
  13425.   if cur_head<>cur_tail then
  13426.     begin link(tail):=link(cur_head); tail:=cur_tail;
  13427.     end;
  13428.   end
  13429. else  begin p:=vpack(link(head),natural); pop_nest;
  13430.   link(tail):=p; tail:=p; space_factor:=1000;
  13431.   end;
  13432. type(p):=unset_node; glue_stretch(p):=0;
  13433. if every_cr<>null then begin_token_list(every_cr,every_cr_text);
  13434. align_peek;
  13435. end; {note that |glue_shrink(p)=0| since |glue_shrink==shift_amount|}
  13436. @ Finally, we will reach the end of the alignment, and we can breathe a
  13437. sigh of relief that memory hasn't overflowed. All the unset boxes will now be
  13438. set so that the columns line up, taking due account of spanned columns.
  13439. @p procedure@?do_assignments; forward;@t\2@>@/
  13440. procedure@?resume_after_display; forward;@t\2@>@/
  13441. procedure@?build_page; forward;@t\2@>@/
  13442. procedure fin_align;
  13443. var @!p,@!q,@!r,@!s,@!u,@!v: pointer; {registers for the list operations}
  13444. @!t,@!w:scaled; {width of column}
  13445. @!o:scaled; {shift offset for unset boxes}
  13446. @!n:halfword; {matching span amount}
  13447. @!rule_save:scaled; {temporary storage for |overfull_rule|}
  13448. @!aux_save:memory_word; {temporary storage for |aux|}
  13449. begin if cur_group<>align_group then confusion("align1");
  13450. @:this can't happen align}{\quad align@>
  13451. unsave; {that |align_group| was for individual entries}
  13452. if cur_group<>align_group then confusion("align0");
  13453. unsave; {that |align_group| was for the whole alignment}
  13454. if nest[nest_ptr-1].mode_field=mmode then o:=display_indent
  13455.   else o:=0;
  13456. @<Go through the preamble list, determining the column widths and
  13457.   changing the alignrecords to dummy unset boxes@>;
  13458. @<Package the preamble list, to determine the actual tabskip glue amounts,
  13459.   and let |p| point to this prototype box@>;
  13460. @<Set the glue in all the unset boxes of the current list@>;
  13461. flush_node_list(p); pop_alignment;
  13462. @<Insert the \(c)current list into its environment@>;
  13463. end;@/
  13464. @t\4@>@<Declare the procedure called |align_peek|@>
  13465. @ It's time now to dismantle the preamble list and to compute the column
  13466. widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
  13467. that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
  13468. contains $w_{ii}$ in its |width| field, and there is also a linked list of
  13469. the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
  13470. these span nodes contain the value $j-i-1+|min_quarterword|$ in their
  13471. |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
  13472. we regard as $-\infty$.
  13473. The final column widths are defined by the formula
  13474. $$w_j=\max_{1\L i\L j}\biggl( w_{ij}-\sum_{i\L k<j}(t_k+w_k)\biggr),$$
  13475. where $t_k$ is the natural width of the tabskip glue between columns
  13476. $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
  13477. |1<=i<=j| (i.e., if every entry that involved column~|j| also involved
  13478. column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
  13479. column~|j|.
  13480. \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
  13481. Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
  13482. Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
  13483. for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
  13484. value is changed to zero and so is the next tabskip.
  13485. @<Go through the preamble list,...@>=
  13486. q:=link(preamble);
  13487. repeat flush_list(u_part(q)); flush_list(v_part(q));
  13488. p:=link(link(q));
  13489. if width(q)=null_flag then
  13490.   @<Nullify |width(q)| and the tabskip glue following this column@>;
  13491. if info(q)<>end_span then
  13492.   @<Merge the widths in the span nodes of |q| with those of |p|,
  13493.     destroying the span nodes of |q|@>;
  13494. type(q):=unset_node; span_count(q):=min_quarterword; height(q):=0;
  13495. depth(q):=0; glue_order(q):=normal; glue_sign(q):=normal;
  13496. glue_stretch(q):=0; glue_shrink(q):=0; q:=p;
  13497. until q=null
  13498. @ @<Nullify |width(q)| and the tabskip glue following this column@>=
  13499. begin width(q):=0; r:=link(q); s:=glue_ptr(r);
  13500. if s<>zero_glue then
  13501.   begin add_glue_ref(zero_glue); delete_glue_ref(s);
  13502.   glue_ptr(r):=zero_glue;
  13503.   end;
  13504. @ Merging of two span-node lists is a typical exercise in the manipulation of
  13505. linearly linked data structures. The essential invariant in the following
  13506. |repeat| loop is that we want to dispense with node |r|, in |q|'s list,
  13507. and |u| is its successor; all nodes of |p|'s list up to and including |s|
  13508. have been processed, and the successor of |s| matches |r| or precedes |r|
  13509. or follows |r|, according as |link(r)=n| or |link(r)>n| or |link(r)<n|.
  13510. @<Merge the widths...@>=
  13511. begin t:=width(q)+width(glue_ptr(link(q)));
  13512. r:=info(q); s:=end_span; info(s):=p; n:=min_quarterword+1;
  13513. repeat width(r):=width(r)-t; u:=info(r);
  13514. while link(r)>n do
  13515.   begin s:=info(s); n:=link(info(s))+1;
  13516.   end;
  13517. if link(r)<n then
  13518.   begin info(r):=info(s); info(s):=r; decr(link(r)); s:=r;
  13519.   end
  13520. else  begin if width(r)>width(info(s)) then width(info(s)):=width(r);
  13521.   free_node(r,span_node_size);
  13522.   end;
  13523. r:=u;
  13524. until r=end_span;
  13525. @ Now the preamble list has been converted to a list of alternating unset
  13526. boxes and tabskip glue, where the box widths are equal to the final
  13527. column sizes. In case of \.{\\valign}, we change the widths to heights,
  13528. so that a correct error message will be produced if the alignment is
  13529. overfull or underfull.
  13530. @<Package the preamble list...@>=
  13531. save_ptr:=save_ptr-2; pack_begin_line:=-mode_line;
  13532. if mode=-vmode then
  13533.   begin rule_save:=overfull_rule;
  13534.   overfull_rule:=0; {prevent rule from being packaged}
  13535.   p:=hpack(preamble,saved(1),saved(0)); overfull_rule:=rule_save;
  13536.   end
  13537. else  begin q:=link(preamble);
  13538.   repeat height(q):=width(q); width(q):=0; q:=link(link(q));
  13539.   until q=null;
  13540.   p:=vpack(preamble,saved(1),saved(0));
  13541.   q:=link(preamble);
  13542.   repeat width(q):=height(q); height(q):=0; q:=link(link(q));
  13543.   until q=null;
  13544.   end;
  13545. pack_begin_line:=0
  13546. @ @<Set the glue in all the unset...@>=
  13547. q:=link(head); s:=head;
  13548. while q<>null do
  13549.   begin if not is_char_node(q) then
  13550.     if type(q)=unset_node then
  13551.       @<Set the unset box |q| and the unset boxes in it@>
  13552.     else if type(q)=rule_node then
  13553.       @<Make the running dimensions in rule |q| extend to the
  13554.         boundaries of the alignment@>;
  13555.   s:=q; q:=link(q);
  13556.   end
  13557. @ @<Make the running dimensions in rule |q| extend...@>=
  13558. begin if is_running(width(q)) then width(q):=width(p);
  13559. if is_running(height(q)) then height(q):=height(p);
  13560. if is_running(depth(q)) then depth(q):=depth(p);
  13561. if o<>0 then
  13562.   begin r:=link(q); link(q):=null; q:=hpack(q,natural);
  13563.   shift_amount(q):=o; link(q):=r; link(s):=q;
  13564.   end;
  13565. @ The unset box |q| represents a row that contains one or more unset boxes,
  13566. depending on how soon \.{\\cr} occurred in that row.
  13567. @<Set the unset box |q| and the unset boxes in it@>=
  13568. begin if mode=-vmode then
  13569.   begin type(q):=hlist_node; width(q):=width(p);
  13570.   end
  13571. else  begin type(q):=vlist_node; height(q):=height(p);
  13572.   end;
  13573. glue_order(q):=glue_order(p); glue_sign(q):=glue_sign(p);
  13574. glue_set(q):=glue_set(p); shift_amount(q):=o;
  13575. r:=link(list_ptr(q)); s:=link(list_ptr(p));
  13576. repeat @<Set the glue in node |r| and change it from an unset node@>;
  13577. r:=link(link(r)); s:=link(link(s));
  13578. until r=null;
  13579. @ A box made from spanned columns will be followed by tabskip glue nodes and
  13580. by empty boxes as if there were no spanning. This permits perfect alignment
  13581. of subsequent entries, and it prevents values that depend on floating point
  13582. arithmetic from entering into the dimensions of any boxes.
  13583. @<Set the glue in node |r|...@>=
  13584. n:=span_count(r); t:=width(s); w:=t; u:=hold_head;
  13585. while n>min_quarterword do
  13586.   begin decr(n);
  13587.   @<Append tabskip glue and an empty box to list |u|,
  13588.     and update |s| and |t| as the prototype nodes are passed@>;
  13589.   end;
  13590. if mode=-vmode then
  13591.   @<Make the unset node |r| into an |hlist_node| of width |w|,
  13592.     setting the glue as if the width were |t|@>
  13593. else @<Make the unset node |r| into a |vlist_node| of height |w|,
  13594.     setting the glue as if the height were |t|@>;
  13595. shift_amount(r):=0;
  13596. if u<>hold_head then {append blank boxes to account for spanned nodes}
  13597.   begin link(u):=link(r); link(r):=link(hold_head); r:=u;
  13598.   end
  13599. @ @<Append tabskip glue and an empty box to list |u|...@>=
  13600. s:=link(s); v:=glue_ptr(s); link(u):=new_glue(v); u:=link(u);
  13601. subtype(u):=tab_skip_code+1; t:=t+width(v);
  13602. if glue_sign(p)=stretching then
  13603.   begin if stretch_order(v)=glue_order(p) then
  13604.     t:=t+round(float(glue_set(p))*stretch(v));
  13605. @^real multiplication@>
  13606.   end
  13607. else if glue_sign(p)=shrinking then
  13608.   begin if shrink_order(v)=glue_order(p) then
  13609.     t:=t-round(float(glue_set(p))*shrink(v));
  13610.   end;
  13611. s:=link(s); link(u):=new_null_box; u:=link(u); t:=t+width(s);
  13612. if mode=-vmode then width(u):=width(s)@+else
  13613.   begin type(u):=vlist_node; height(u):=width(s);
  13614.   end
  13615. @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
  13616. begin height(r):=height(q); depth(r):=depth(q);
  13617. if t=width(r) then
  13618.   begin glue_sign(r):=normal; glue_order(r):=normal;
  13619.   set_glue_ratio_zero(glue_set(r));
  13620.   end
  13621. else if t>width(r) then
  13622.   begin glue_sign(r):=stretching;
  13623.   if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
  13624.   else glue_set(r):=unfloat((t-width(r))/glue_stretch(r));
  13625. @^real division@>
  13626.   end
  13627. else  begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
  13628.   if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
  13629.   else if (glue_order(r)=normal)and(width(r)-t>glue_shrink(r)) then
  13630.     set_glue_ratio_one(glue_set(r))
  13631.   else glue_set(r):=unfloat((width(r)-t)/glue_shrink(r));
  13632.   end;
  13633. width(r):=w; type(r):=hlist_node;
  13634. @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
  13635. begin width(r):=width(q);
  13636. if t=height(r) then
  13637.   begin glue_sign(r):=normal; glue_order(r):=normal;
  13638.   set_glue_ratio_zero(glue_set(r));
  13639.   end
  13640. else if t>height(r) then
  13641.   begin glue_sign(r):=stretching;
  13642.   if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
  13643.   else glue_set(r):=unfloat((t-height(r))/glue_stretch(r));
  13644. @^real division@>
  13645.   end
  13646. else  begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
  13647.   if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
  13648.   else if (glue_order(r)=normal)and(height(r)-t>glue_shrink(r)) then
  13649.     set_glue_ratio_one(glue_set(r))
  13650.   else glue_set(r):=unfloat((height(r)-t)/glue_shrink(r));
  13651.   end;
  13652. height(r):=w; type(r):=vlist_node;
  13653. @ We now have a completed alignment, in the list that starts at |head|
  13654. and ends at |tail|. This list will be merged with the one that encloses
  13655. it. (In case the enclosing mode is |mmode|, for displayed formulas,
  13656. we will need to insert glue before and after the display; that part of the
  13657. program will be deferred until we're more familiar with such operations.)
  13658. In horizontal mode, the |clang| part of |aux| is undefined; an over-cautious
  13659. \PASCAL\ runtime system may complain about this.
  13660. @^dirty Pascal@>
  13661. @<Insert the \(c)current list into its environment@>=
  13662. aux_save:=aux; p:=link(head); q:=tail; pop_nest;
  13663. if mode=mmode then @<Finish an alignment in a display@>
  13664. else  begin aux:=aux_save; link(tail):=p;
  13665.   if p<>null then tail:=q;
  13666.   if mode=vmode then build_page;
  13667.   end
  13668. @* \[38] Breaking paragraphs into lines.
  13669. We come now to what is probably the most interesting algorithm of \TeX:
  13670. the mechanism for choosing the ``best possible'' breakpoints that yield
  13671. the individual lines of a paragraph. \TeX's line-breaking algorithm takes
  13672. a given horizontal list and converts it to a sequence of boxes that are
  13673. appended to the current vertical list. In the course of doing this, it
  13674. creates a special data structure containing three kinds of records that are
  13675. not used elsewhere in \TeX. Such nodes are created while a paragraph is
  13676. being processed, and they are destroyed afterwards; thus, the other parts
  13677. of \TeX\ do not need to know anything about how line-breaking is done.
  13678. The method used here is based on an approach devised by Michael F. Plass and
  13679. @^Plass, Michael Frederick@>
  13680. @^Knuth, Donald Ervin@>
  13681. the author in 1977, subsequently generalized and improved by the same two
  13682. people in 1980. A detailed discussion appears in {\sl SOFTWARE---Practice
  13683. \AM\ Experience \bf11} (1981), 1119--1184, where it is shown that the
  13684. line-breaking problem can be regarded as a special case of the problem of
  13685. computing the shortest path in an acyclic network. The cited paper includes
  13686. numerous examples and describes the history of line breaking as it has been
  13687. practiced by printers through the ages. The present implementation adds two
  13688. new ideas to the algorithm of 1980: memory space requirements are considerably
  13689. reduced by using smaller records for inactive nodes than for active ones,
  13690. and arithmetic overflow is avoided by using ``delta distances'' instead of
  13691. keeping track of the total distance from the beginning of the paragraph to the
  13692. current point.
  13693. @ The |line_break| procedure should be invoked only in horizontal mode; it
  13694. leaves that mode and places its output into the current vlist of the
  13695. enclosing vertical mode (or internal vertical mode).
  13696. There is one explicit parameter:  |final_widow_penalty| is the amount of
  13697. additional penalty to be inserted before the final line of the paragraph.
  13698. There are also a number of implicit parameters: The hlist to be broken
  13699. starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
  13700. enclosing semantic level tells where the paragraph should begin in the
  13701. sequence of line numbers, in case hanging indentation or \.{\\parshape}
  13702. are in use; |prev_graf| is zero unless this paragraph is being continued
  13703. after a displayed formula.  Other implicit parameters, such as the
  13704. |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
  13705. in |eqtb|.
  13706. After |line_break| has acted, it will have updated the current vlist and the
  13707. value of |prev_graf|. Furthermore, the global variable |just_box| will
  13708. point to the final box created by |line_break|, so that the width of this
  13709. line can be ascertained when it is necessary to decide whether to use
  13710. |above_display_skip| or |above_display_short_skip| before a displayed formula.
  13711. @<Glob...@>=
  13712. @!just_box:pointer; {the |hlist_node| for the last line of the new paragraph}
  13713. @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
  13714. itself---we must build it up little by little, somewhat more cautiously
  13715. than we have done with the simpler procedures of \TeX. Here is the
  13716. general outline.
  13717. @p@t\4@>@<Declare subprocedures for |line_break|@>
  13718. procedure line_break(@!final_widow_penalty:integer);
  13719. label done,done1,done2,done3,done4,done5,continue;
  13720. var @<Local variables for line breaking@>@;
  13721. begin pack_begin_line:=mode_line; {this is for over/underfull box messages}
  13722. @<Get ready to start line breaking@>;
  13723. @<Find optimal breakpoints@>;
  13724. @<Break the paragraph at the chosen breakpoints, justify the resulting lines
  13725. to the correct widths, and append them to the current vertical list@>;
  13726. @<Clean up the memory by removing the break nodes@>;
  13727. pack_begin_line:=0;
  13728. @ The first task is to move the list from |head| to |temp_head| and go
  13729. into the enclosing semantic level. We also append the \.{\\parfillskip}
  13730. glue to the end of the paragraph, removing a space (or other glue node) if
  13731. it was there, since spaces usually precede blank lines and instances of
  13732. `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
  13733. it will never be considered as a potential breakpoint.
  13734. This code assumes that a |glue_node| and a |penalty_node| occupy the
  13735. same number of |mem|~words.
  13736. @^data structure assumptions@>
  13737. @<Get ready to start...@>=
  13738. link(temp_head):=link(head);
  13739. if is_char_node(tail) then tail_append(new_penalty(inf_penalty))
  13740. else if type(tail)<>glue_node then tail_append(new_penalty(inf_penalty))
  13741. else  begin type(tail):=penalty_node; delete_glue_ref(glue_ptr(tail));
  13742.   flush_node_list(leader_ptr(tail)); penalty(tail):=inf_penalty;
  13743.   end;
  13744. link(tail):=new_param_glue(par_fill_skip_code);
  13745. init_cur_lang:=prev_graf mod @'200000;
  13746. init_l_hyf:=prev_graf div @'20000000;
  13747. init_r_hyf:=(prev_graf div @'200000) mod @'100;
  13748. pop_nest;
  13749. @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
  13750. each break that is {\sl feasible}, in the sense that there is a way to end
  13751. a line at the given place without requiring any line to stretch more than
  13752. a given tolerance. A break node is characterized by three things: the position
  13753. of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
  13754. or |disc_node|); the ordinal number of the line that will follow this
  13755. breakpoint; and the fitness classification of the line that has just
  13756. ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
  13757. @d tight_fit=3 {fitness classification for lines shrinking 0.5 to 1.0 of their
  13758.   shrinkability}
  13759. @d loose_fit=1 {fitness classification for lines stretching 0.5 to 1.0 of their
  13760.   stretchability}
  13761. @d very_loose_fit=0 {fitness classification for lines stretching more than
  13762.   their stretchability}
  13763. @d decent_fit=2 {fitness classification for all other lines}
  13764. @ The algorithm essentially determines the best possible way to achieve
  13765. each feasible combination of position, line, and fitness. Thus, it answers
  13766. questions like, ``What is the best way to break the opening part of the
  13767. paragraph so that the fourth line is a tight line ending at such-and-such
  13768. a place?'' However, the fact that all lines are to be the same length
  13769. after a certain point makes it possible to regard all sufficiently large
  13770. line numbers as equivalent, when the looseness parameter is zero, and this
  13771. makes it possible for the algorithm to save space and time.
  13772. An ``active node'' and a ``passive node'' are created in |mem| for each
  13773. feasible breakpoint that needs to be considered. Active nodes are three
  13774. words long and passive nodes are two words long. We need active nodes only
  13775. for breakpoints near the place in the paragraph that is currently being
  13776. examined, so they are recycled within a comparatively short time after
  13777. they are created.
  13778. @ An active node for a given breakpoint contains six fields:
  13779. \yskip\hang|link| points to the next node in the list of active nodes; the
  13780. last active node has |link=last_active|.
  13781. \yskip\hang|break_node| points to the passive node associated with this
  13782. breakpoint.
  13783. \yskip\hang|line_number| is the number of the line that follows this
  13784. breakpoint.
  13785. \yskip\hang|fitness| is the fitness classification of the line ending at this
  13786. breakpoint.
  13787. \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
  13788. whether this breakpoint is a |disc_node|.
  13789. \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
  13790. lines leading from the beginning of the paragraph to this breakpoint.
  13791. \yskip\noindent
  13792. The value of |link(active)| points to the first active node on a linked list
  13793. of all currently active nodes. This list is in order by |line_number|,
  13794. except that nodes with |line_number>easy_line| may be in any order relative
  13795. to each other.
  13796. @d active_node_size=3 {number of words in active nodes}
  13797. @d fitness==subtype {|very_loose_fit..tight_fit| on final line for this break}
  13798. @d break_node==rlink {pointer to the corresponding passive node}
  13799. @d line_number==llink {line that begins at this breakpoint}
  13800. @d total_demerits(#)==mem[#+2].int {the quantity that \TeX\ minimizes}
  13801. @d unhyphenated=0 {the |type| of a normal active break node}
  13802. @d hyphenated=1 {the |type| of an active node that breaks at a |disc_node|}
  13803. @d last_active==active {the active list ends where it begins}
  13804. @ @<Initialize the special list heads...@>=
  13805. type(last_active):=hyphenated; line_number(last_active):=max_halfword;
  13806. subtype(last_active):=0; {the |subtype| is never examined by the algorithm}
  13807. @ The passive node for a given breakpoint contains only four fields:
  13808. \yskip\hang|link| points to the passive node created just before this one,
  13809. if any, otherwise it is |null|.
  13810. \yskip\hang|cur_break| points to the position of this breakpoint in the
  13811. horizontal list for the paragraph being broken.
  13812. \yskip\hang|prev_break| points to the passive node that should precede this
  13813. one in an optimal path to this breakpoint.
  13814. \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
  13815. one created during the current pass. (This field is used only when
  13816. printing out detailed statistics about the line-breaking calculations.)
  13817. \yskip\noindent
  13818. There is a global variable called |passive| that points to the most
  13819. recently created passive node. Another global variable, |printed_node|,
  13820. is used to help print out the paragraph when detailed information about
  13821. the line-breaking computation is being displayed.
  13822. @d passive_node_size=2 {number of words in passive nodes}
  13823. @d cur_break==rlink {in passive node, points to position of this breakpoint}
  13824. @d prev_break==llink {points to passive node that should precede this one}
  13825. @d serial==info {serial number for symbolic identification}
  13826. @<Glob...@>=
  13827. @!passive:pointer; {most recent node on passive list}
  13828. @!printed_node:pointer; {most recent node that has been printed}
  13829. @!pass_number:halfword; {the number of passive nodes allocated on this pass}
  13830. @ The active list also contains ``delta'' nodes that help the algorithm
  13831. compute the badness of individual lines. Such nodes appear only between two
  13832. active nodes, and they have |type=delta_node|. If |p| and |r| are active nodes
  13833. and if |q| is a delta node between them, so that |link(p)=q| and |link(q)=r|,
  13834. then |q| tells the space difference between lines in the horizontal list that
  13835. start after breakpoint |p| and lines that start after breakpoint |r|. In
  13836. other words, if we know the length of the line that starts after |p| and
  13837. ends at our current position, then the corresponding length of the line that
  13838. starts after |r| is obtained by adding the amounts in node~|q|. A delta node
  13839. contains six scaled numbers, since it must record the net change in glue
  13840. stretchability with respect to all orders of infinity. The natural width
  13841. difference appears in |mem[q+1].sc|; the stretch differences in units of
  13842. pt, fil, fill, and filll appear in |mem[q+2..q+5].sc|; and the shrink difference
  13843. appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
  13844. @d delta_node_size=7 {number of words in a delta node}
  13845. @d delta_node=2 {|type| field in a delta node}
  13846. @ As the algorithm runs, it maintains a set of six delta-like registers
  13847. for the length of the line following the first active breakpoint to the
  13848. current position in the given hlist. When it makes a pass through the
  13849. active list, it also maintains a similar set of six registers for the
  13850. length following the active breakpoint of current interest. A third set
  13851. holds the length of an empty line (namely, the sum of \.{\\leftskip} and
  13852. \.{\\rightskip}); and a fourth set is used to create new delta nodes.
  13853. When we pass a delta node we want to do operations like
  13854. $$\hbox{\ignorespaces|for
  13855. k:=1 to 6 do cur_active_width[k]:=cur_active_width[k]+mem[q+k].sc|};$$ and we
  13856. want to do this without the overhead of |for| loops. The |do_all_six|
  13857. macro makes such six-tuples convenient.
  13858. @d do_all_six(#)==#(1);#(2);#(3);#(4);#(5);#(6)
  13859. @<Glo...@>=
  13860. @!active_width:array[1..6] of scaled;
  13861.   {distance from first active node to~|cur_p|}
  13862. @!cur_active_width:array[1..6] of scaled; {distance from current active node}
  13863. @!background:array[1..6] of scaled; {length of an ``empty'' line}
  13864. @!break_width:array[1..6] of scaled; {length being computed after current break}
  13865. @ Let's state the principles of the delta nodes more precisely and concisely,
  13866. so that the following programs will be less obscure. For each legal
  13867. breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
  13868. $\beta(p)$ such that the length of material in a line from breakpoint~|p|
  13869. to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
  13870. Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
  13871. the beginning of the paragraph to a point ``after'' a break at |p| and to a
  13872. point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
  13873. namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
  13874. Suppose, for example, that the paragraph consists entirely of alternating
  13875. boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
  13876. let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
  13877. represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
  13878. at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
  13879. x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
  13880. $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
  13881. -\alpha(p_2)$.
  13882. The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
  13883. shrinkability as well as a natural width. If we were to compute $\alpha(p)$
  13884. and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
  13885. the multiprecise numbers would have to be kept in the active nodes.
  13886. \TeX\ avoids this problem by working entirely with relative differences
  13887. or ``deltas.'' Suppose, for example, that the active list contains
  13888. $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
  13889. and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
  13890. and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
  13891. currently positioned at some other breakpoint |p|, the |active_width| array
  13892. contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
  13893. the list of active nodes and considering a tentative line that runs from
  13894. $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
  13895. $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
  13896. we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
  13897. is just $\delta_2$, which appears in the active list between $a_2$ and
  13898. $a_3$. The |background| array contains $\gamma$. The |break_width| array
  13899. will be used to calculate values of new delta nodes when the active
  13900. list is being updated.
  13901. @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
  13902. include ``infinite'' shrinkability; that is why the algorithm maintains
  13903. four registers for stretching but only one for shrinking. If the user tries to
  13904. introduce infinite shrinkability, the shrinkability will be reset to finite
  13905. and an error message will be issued. A boolean variable |no_shrink_error_yet|
  13906. prevents this error message from appearing more than once per paragraph.
  13907. @d check_shrinkage(#)==if (shrink_order(#)<>normal)and(shrink(#)<>0) then
  13908.   begin #:=finite_shrink(#);
  13909.   end
  13910. @<Glob...@>=
  13911. @!no_shrink_error_yet:boolean; {have we complained about infinite shrinkage?}
  13912. @ @<Declare subprocedures for |line_break|@>=
  13913. function finite_shrink(@!p:pointer):pointer; {recovers from infinite shrinkage}
  13914. var q:pointer; {new glue specification}
  13915. begin if no_shrink_error_yet then
  13916.   begin no_shrink_error_yet:=false;
  13917.   print_err("Infinite glue shrinkage found in a paragraph");
  13918. @.Infinite glue shrinkage...@>
  13919.   help5("The paragraph just ended includes some glue that has")@/
  13920.   ("infinite shrinkability, e.g., `\hskip 0pt minus 1fil'.")@/
  13921.   ("Such glue doesn't belong there---it allows a paragraph")@/
  13922.   ("of any length to fit on one line. But it's safe to proceed,")@/
  13923.   ("since the offensive shrinkability has been made finite.");
  13924.   error;
  13925.   end;
  13926. q:=new_spec(p); shrink_order(q):=normal;
  13927. delete_glue_ref(p); finite_shrink:=q;
  13928. @ @<Get ready to start...@>=
  13929. no_shrink_error_yet:=true;@/
  13930. check_shrinkage(left_skip); check_shrinkage(right_skip);@/
  13931. q:=left_skip; r:=right_skip; background[1]:=width(q)+width(r);@/
  13932. background[2]:=0; background[3]:=0; background[4]:=0; background[5]:=0;@/
  13933. background[2+stretch_order(q)]:=stretch(q);@/
  13934. background[2+stretch_order(r)]:=@|background[2+stretch_order(r)]+stretch(r);@/
  13935. background[6]:=shrink(q)+shrink(r);
  13936. @ A pointer variable |cur_p| runs through the given horizontal list as we look
  13937. for breakpoints. This variable is global, since it is used both by |line_break|
  13938. and by its subprocedure |try_break|.
  13939. Another global variable called |threshold| is used to determine the feasibility
  13940. of individual lines: breakpoints are feasible if there is a way to reach
  13941. them without creating lines whose badness exceeds |threshold|.  (The
  13942. badness is compared to |threshold| before penalties are added, so that
  13943. penalty values do not affect the feasibility of breakpoints, except that
  13944. no break is allowed when the penalty is 10000 or more.) If |threshold|
  13945. is 10000 or more, all legal breaks are considered feasible, since the
  13946. |badness| function specified above never returns a value greater than~10000.
  13947. Up to three passes might be made through the paragraph in an attempt to find at
  13948. least one set of feasible breakpoints. On the first pass, we have
  13949. |threshold=pretolerance| and |second_pass=final_pass=false|.
  13950. If this pass fails to find a
  13951. feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
  13952. |true|, and an attempt is made to hyphenate as many words as possible.
  13953. If that fails too, we add |emergency_stretch| to the background
  13954. stretchability and set |final_pass=true|.
  13955. @<Glob...@>=
  13956. @!cur_p:pointer; {the current breakpoint under consideration}
  13957. @!second_pass:boolean; {is this our second attempt to break this paragraph?}
  13958. @!final_pass:boolean; {is this our final attempt to break this paragraph?}
  13959. @!threshold:integer; {maximum badness on feasible lines}
  13960. @ The heart of the line-breaking procedure is `|try_break|', a subroutine
  13961. that tests if the current breakpoint |cur_p| is feasible, by running
  13962. through the active list to see what lines of text can be made from active
  13963. nodes to~|cur_p|.  If feasible breaks are possible, new break nodes are
  13964. created.  If |cur_p| is too far from an active node, that node is
  13965. deactivated.
  13966. The parameter |pi| to |try_break| is the penalty associated
  13967. with a break at |cur_p|; we have |pi=eject_penalty| if the break is forced,
  13968. and |pi=inf_penalty| if the break is illegal.
  13969. The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
  13970. depending on whether or not the current break is at a |disc_node|. The
  13971. end of a paragraph is also regarded as `|hyphenated|'; this case is
  13972. distinguishable by the condition |cur_p=null|.
  13973. @d copy_to_cur_active(#)==cur_active_width[#]:=active_width[#]
  13974. @d deactivate=60 {go here when node |r| should be deactivated}
  13975. @<Declare subprocedures for |line_break|@>=
  13976. procedure try_break(@!pi:integer;@!break_type:small_number);
  13977. label exit,done,done1,continue,deactivate;
  13978. var r:pointer; {runs through the active list}
  13979. @!prev_r:pointer; {stays a step behind |r|}
  13980. @!old_l:halfword; {maximum line number in current equivalence class of lines}
  13981. @!no_break_yet:boolean; {have we found a feasible break at |cur_p|?}
  13982. @<Other local variables for |try_break|@>@;
  13983. begin @<Make sure that |pi| is in the proper range@>;
  13984. no_break_yet:=true; prev_r:=active; old_l:=0;
  13985. do_all_six(copy_to_cur_active);
  13986. loop@+  begin continue: r:=link(prev_r);
  13987.   @<If node |r| is of type |delta_node|, update |cur_active_width|,
  13988.     set |prev_r| and |prev_prev_r|, then |goto continue|@>;
  13989.   @<If a line number class has ended, create new active nodes for
  13990.     the best feasible breaks in that class; then |return|
  13991.     if |r=last_active|, otherwise compute the new |line_width|@>;
  13992.   @<Consider the demerits for a line from |r| to |cur_p|;
  13993.     deactivate node |r| if it should no longer be active;
  13994.     then |goto continue| if a line from |r| to |cur_p| is infeasible,
  13995.     otherwise record a new feasible break@>;
  13996.   end;
  13997. exit: @!stat @<Update the value of |printed_node| for
  13998.   symbolic displays@>@+tats@;
  13999. @ @<Other local variables for |try_break|@>=
  14000. @!prev_prev_r:pointer; {a step behind |prev_r|, if |type(prev_r)=delta_node|}
  14001. @!s:pointer; {runs through nodes ahead of |cur_p|}
  14002. @!q:pointer; {points to a new node being created}
  14003. @!v:pointer; {points to a glue specification or a node ahead of |cur_p|}
  14004. @!t:integer; {node count, if |cur_p| is a discretionary node}
  14005. @!f:internal_font_number; {used in character width calculation}
  14006. @!l:halfword; {line number of current active node}
  14007. @!node_r_stays_active:boolean; {should node |r| remain in the active list?}
  14008. @!line_width:scaled; {the current line will be justified to this width}
  14009. @!fit_class:very_loose_fit..tight_fit; {possible fitness class of test line}
  14010. @!b:halfword; {badness of test line}
  14011. @!d:integer; {demerits of test line}
  14012. @!artificial_demerits:boolean; {has |d| been forced to zero?}
  14013. @!save_link:pointer; {temporarily holds value of |link(cur_p)|}
  14014. @!shortfall:scaled; {used in badness calculations}
  14015. @ @<Make sure that |pi| is in the proper range@>=
  14016. if abs(pi)>=inf_penalty then
  14017.   if pi>0 then return {this breakpoint is inhibited by infinite penalty}
  14018.   else pi:=eject_penalty {this breakpoint will be forced}
  14019. @ The following code uses the fact that |type(last_active)<>delta_node|.
  14020. @d update_width(#)==@|
  14021.   cur_active_width[#]:=cur_active_width[#]+mem[r+#].sc
  14022. @<If node |r|...@>=
  14023. @^inner loop@>
  14024. if type(r)=delta_node then
  14025.   begin do_all_six(update_width);
  14026.   prev_prev_r:=prev_r; prev_r:=r; goto continue;
  14027.   end
  14028. @ As we consider various ways to end a line at |cur_p|, in a given line number
  14029. class, we keep track of the best total demerits known, in an array with
  14030. one entry for each of the fitness classifications. For example,
  14031. |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
  14032. line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
  14033. points to the passive node for the break before~|cur_p| that achieves such
  14034. an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
  14035. active node corresponding to |best_place[tight_fit]|. When no feasible break
  14036. sequence is known, the |minimal_demerits| entries will be equal to
  14037. |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
  14038. keeps track of the smallest value in the |minimal_demerits| array.
  14039. @d awful_bad==@'7777777777 {more than a billion demerits}
  14040. @<Global...@>=
  14041. @!minimal_demerits:array[very_loose_fit..tight_fit] of integer; {best total
  14042.   demerits known for current line class and position, given the fitness}
  14043. @!minimum_demerits:integer; {best total demerits known for current line class
  14044.   and position}
  14045. @!best_place:array[very_loose_fit..tight_fit] of pointer; {how to achieve
  14046.   |minimal_demerits|}
  14047. @!best_pl_line:array[very_loose_fit..tight_fit] of halfword; {corresponding
  14048.   line number}
  14049. @ @<Get ready to start...@>=
  14050. minimum_demerits:=awful_bad;
  14051. minimal_demerits[tight_fit]:=awful_bad;
  14052. minimal_demerits[decent_fit]:=awful_bad;
  14053. minimal_demerits[loose_fit]:=awful_bad;
  14054. minimal_demerits[very_loose_fit]:=awful_bad;
  14055. @ The first part of the following code is part of \TeX's inner loop, so
  14056. we don't want to waste any time. The current active node, namely node |r|,
  14057. contains the line number that will be considered next. At the end of the
  14058. list we have arranged the data structure so that |r=last_active| and
  14059. |line_number(last_active)>old_l|.
  14060. @^inner loop@>
  14061. @<If a line number class...@>=
  14062. begin l:=line_number(r);
  14063. if l>old_l then
  14064.   begin {now we are no longer in the inner loop}
  14065.   if (minimum_demerits<awful_bad)and@|
  14066.       ((old_l<>easy_line)or(r=last_active)) then
  14067.     @<Create new active nodes for the best feasible breaks
  14068.       just found@>;
  14069.   if r=last_active then return;
  14070.   @<Compute the new line width@>;
  14071.   end;
  14072. @ It is not necessary to create new active nodes having |minimal_demerits|
  14073. greater than
  14074. |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
  14075. be chosen in the final paragraph breaks. This observation allows us to
  14076. omit a substantial number of feasible breakpoints from further consideration.
  14077. @<Create new active nodes...@>=
  14078. begin if no_break_yet then @<Compute the values of |break_width|@>;
  14079. @<Insert a delta node to prepare for breaks at |cur_p|@>;
  14080. if abs(adj_demerits)>=awful_bad-minimum_demerits then
  14081.   minimum_demerits:=awful_bad-1
  14082. else minimum_demerits:=minimum_demerits+abs(adj_demerits);
  14083. for fit_class:=very_loose_fit to tight_fit do
  14084.   begin if minimal_demerits[fit_class]<=minimum_demerits then
  14085.     @<Insert a new active node
  14086.       from |best_place[fit_class]| to |cur_p|@>;
  14087.   minimal_demerits[fit_class]:=awful_bad;
  14088.   end;
  14089. minimum_demerits:=awful_bad;
  14090. @<Insert a delta node to prepare for the next active node@>;
  14091. @ When we insert a new active node for a break at |cur_p|, suppose this
  14092. new node is to be placed just before active node |a|; then we essentially
  14093. want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
  14094. $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
  14095. in the notation explained above.  The |cur_active_width| array now holds
  14096. $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
  14097. subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
  14098. \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
  14099. line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
  14100. The |break_width| is usually negative, since it consists of the background
  14101. (which is normally zero) minus the width of nodes following~|cur_p| that are
  14102. eliminated after a break. If, for example, node |cur_p| is a glue node, the
  14103. width of this glue is subtracted from the background; and we also look
  14104. ahead to eliminate all subsequent glue and penalty and kern and math
  14105. nodes, subtracting their widths as well.
  14106. Kern nodes do not disappear at a line break unless they are |explicit|.
  14107. @d set_break_width_to_background(#)==break_width[#]:=background[#]
  14108. @<Compute the values of |break...@>=
  14109. begin no_break_yet:=false; do_all_six(set_break_width_to_background);
  14110. s:=cur_p;
  14111. if break_type>unhyphenated then if cur_p<>null then
  14112.   @<Compute the discretionary |break_width| values@>;
  14113. while s<>null do
  14114.   begin if is_char_node(s) then goto done;
  14115.   case type(s) of
  14116.   glue_node:@<Subtract glue from |break_width|@>;
  14117.   penalty_node: do_nothing;
  14118.   math_node: break_width[1]:=break_width[1]-width(s);
  14119.   kern_node: if subtype(s)<>explicit then goto done
  14120.     else break_width[1]:=break_width[1]-width(s);
  14121.   othercases goto done
  14122.   endcases;@/
  14123.   s:=link(s);
  14124.   end;
  14125. done: end
  14126. @ @<Subtract glue from |break...@>=
  14127. begin v:=glue_ptr(s); break_width[1]:=break_width[1]-width(v);
  14128. break_width[2+stretch_order(v)]:=break_width[2+stretch_order(v)]-stretch(v);
  14129. break_width[6]:=break_width[6]-shrink(v);
  14130. @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
  14131. |cur_p|'' has to be defined properly so that the other calculations work out.
  14132. Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
  14133. text has length $l_1$, and the replacement text has length |l|. Suppose
  14134. also that |q| is the node following the replacement text. Then length of a
  14135. line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
  14136. where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
  14137. plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
  14138. If the post-break text of the discretionary is empty, a break may also
  14139. discard~|q|; in that unusual case we subtract the length of~|q| and any
  14140. other nodes that will be discarded after the discretionary break.
  14141. The value of $l_0$ need not be computed, since |line_break| will put
  14142. it into the global variable |disc_width| before calling |try_break|.
  14143. @<Glob...@>=
  14144. @!disc_width:scaled; {the length of discretionary material preceding a break}
  14145. @ @<Compute the discretionary |break...@>=
  14146. begin t:=replace_count(cur_p); v:=cur_p; s:=post_break(cur_p);
  14147. while t>0 do
  14148.   begin decr(t); v:=link(v);
  14149.   @<Subtract the width of node |v| from |break_width|@>;
  14150.   end;
  14151. while s<>null do
  14152.   begin @<Add the width of node |s| to |break_width|@>;
  14153.   s:=link(s);
  14154.   end;
  14155. break_width[1]:=break_width[1]+disc_width;
  14156. if post_break(cur_p)=null then s:=link(v);
  14157.           {nodes may be discardable after the break}
  14158. @ Replacement texts and discretionary texts are supposed to contain
  14159. only character nodes, kern nodes, ligature nodes, and box or rule nodes.
  14160. @<Subtract the width of node |v|...@>=
  14161. if is_char_node(v) then
  14162.   begin f:=font(v);
  14163.   break_width[1]:=break_width[1]-char_width(f)(char_info(f)(character(v)));
  14164.   end
  14165. else  case type(v) of
  14166.   ligature_node: begin f:=font(lig_char(v));@/
  14167.     break_width[1]:=@|break_width[1]-
  14168.       char_width(f)(char_info(f)(character(lig_char(v))));
  14169.     end;
  14170.   hlist_node,vlist_node,rule_node,kern_node:
  14171.     break_width[1]:=break_width[1]-width(v);
  14172.   othercases confusion("disc1")
  14173. @:this can't happen disc1}{\quad disc1@>
  14174.   endcases
  14175. @ @<Add the width of node |s| to |b...@>=
  14176. if is_char_node(s) then
  14177.   begin f:=font(s);
  14178.   break_width[1]:=@|break_width[1]+char_width(f)(char_info(f)(character(s)));
  14179.   end
  14180. else  case type(s) of
  14181.   ligature_node: begin f:=font(lig_char(s));
  14182.     break_width[1]:=break_width[1]+
  14183.       char_width(f)(char_info(f)(character(lig_char(s))));
  14184.     end;
  14185.   hlist_node,vlist_node,rule_node,kern_node:
  14186.     break_width[1]:=break_width[1]+width(s);
  14187.   othercases confusion("disc2")
  14188. @:this can't happen disc2}{\quad disc2@>
  14189.   endcases
  14190. @ We use the fact that |type(active)<>delta_node|.
  14191. @d convert_to_break_width(#)==@|
  14192.   mem[prev_r+#].sc:=@|@t\hskip10pt@>mem[prev_r+#].sc
  14193.   -cur_active_width[#]+break_width[#]
  14194. @d store_break_width(#)==active_width[#]:=break_width[#]
  14195. @d new_delta_to_break_width(#)==@|
  14196.   mem[q+#].sc:=break_width[#]-cur_active_width[#]
  14197. @<Insert a delta node to prepare for breaks at |cur_p|@>=
  14198. if type(prev_r)=delta_node then {modify an existing delta node}
  14199.   begin do_all_six(convert_to_break_width);
  14200.   end
  14201. else if prev_r=active then {no delta node needed at the beginning}
  14202.   begin do_all_six(store_break_width);
  14203.   end
  14204. else  begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
  14205.   subtype(q):=0; {the |subtype| is not used}
  14206.   do_all_six(new_delta_to_break_width);
  14207.   link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
  14208.   end
  14209. @ When the following code is performed, we will have just inserted at
  14210. least one active node before |r|, so |type(prev_r)<>delta_node|.
  14211. @d new_delta_from_break_width(#)==@|mem[q+#].sc:=
  14212.     cur_active_width[#]-break_width[#]
  14213. @<Insert a delta node to prepare for the next active node@>=
  14214. if r<>last_active then
  14215.   begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
  14216.   subtype(q):=0; {the |subtype| is not used}
  14217.   do_all_six(new_delta_from_break_width);
  14218.   link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
  14219.   end
  14220. @ When we create an active node, we also create the corresponding
  14221. passive node.
  14222. @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
  14223. begin q:=get_node(passive_node_size);
  14224. link(q):=passive; passive:=q; cur_break(q):=cur_p;
  14225. @!stat incr(pass_number); serial(q):=pass_number;@+tats@;@/
  14226. prev_break(q):=best_place[fit_class];@/
  14227. q:=get_node(active_node_size); break_node(q):=passive;
  14228. line_number(q):=best_pl_line[fit_class]+1;
  14229. fitness(q):=fit_class; type(q):=break_type;
  14230. total_demerits(q):=minimal_demerits[fit_class];
  14231. link(q):=r; link(prev_r):=q; prev_r:=q;
  14232. @!stat if tracing_paragraphs>0 then
  14233.   @<Print a symbolic description of the new break node@>;
  14234. tats@;@/
  14235. @ @<Print a symbolic description of the new break node@>=
  14236. begin print_nl("@@@@"); print_int(serial(passive));
  14237. @.\AT!\AT!@>
  14238. print(": line "); print_int(line_number(q)-1);
  14239. print_char("."); print_int(fit_class);
  14240. if break_type=hyphenated then print_char("-");
  14241. print(" t="); print_int(total_demerits(q));
  14242. print(" -> @@@@");
  14243. if prev_break(passive)=null then print_char("0")
  14244. else print_int(serial(prev_break(passive)));
  14245. @ The length of lines depends on whether the user has specified
  14246. \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
  14247. points to a $(2n+1)$-word record in |mem|, where the |info| in the first
  14248. word contains the value of |n|, and the other $2n$ words contain the left
  14249. margins and line lengths for the first |n| lines of the paragraph; the
  14250. specifications for line |n| apply to all subsequent lines. If
  14251. |par_shape_ptr=null|, the shape of the paragraph depends on the value of
  14252. |n=hang_after|; if |n>=0|, hanging indentation takes place on lines |n+1|,
  14253. |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
  14254. n\vert$. When hanging indentation is active, the left margin is
  14255. |hang_indent|, if |hang_indent>=0|, else it is 0; the line length is
  14256. $|hsize|-\vert|hang_indent|\vert$. The normal setting is
  14257. |par_shape_ptr=null|, |hang_after=1|, and |hang_indent=0|.
  14258. Note that if |hang_indent=0|, the value of |hang_after| is irrelevant.
  14259. @^length of lines@> @^hanging indentation@>
  14260. @<Glob...@>=
  14261. @!easy_line:halfword; {line numbers |>easy_line| are equivalent in break nodes}
  14262. @!last_special_line:halfword; {line numbers |>last_special_line| all have
  14263.   the same width}
  14264. @!first_width:scaled; {the width of all lines |<=last_special_line|, if
  14265.   no \.{\\parshape} has been specified}
  14266. @!second_width:scaled; {the width of all lines |>last_special_line|}
  14267. @!first_indent:scaled; {left margin to go with |first_width|}
  14268. @!second_indent:scaled; {left margin to go with |second_width|}
  14269. @ We compute the values of |easy_line| and the other local variables relating
  14270. to line length when the |line_break| procedure is initializing itself.
  14271. @<Get ready to start...@>=
  14272. if par_shape_ptr=null then
  14273.   if hang_indent=0 then
  14274.     begin last_special_line:=0; second_width:=hsize;
  14275.     second_indent:=0;
  14276.     end
  14277.   else @<Set line length parameters in preparation for hanging indentation@>
  14278. else  begin last_special_line:=info(par_shape_ptr)-1;
  14279.   second_width:=mem[par_shape_ptr+2*(last_special_line+1)].sc;
  14280.   second_indent:=mem[par_shape_ptr+2*last_special_line+1].sc;
  14281.   end;
  14282. if looseness=0 then easy_line:=last_special_line
  14283. else easy_line:=max_halfword
  14284. @ @<Set line length parameters in preparation for hanging indentation@>=
  14285. begin last_special_line:=abs(hang_after);
  14286. if hang_after<0 then
  14287.   begin first_width:=hsize-abs(hang_indent);
  14288.   if hang_indent>=0 then first_indent:=hang_indent
  14289.   else first_indent:=0;
  14290.   second_width:=hsize; second_indent:=0;
  14291.   end
  14292. else  begin first_width:=hsize; first_indent:=0;
  14293.   second_width:=hsize-abs(hang_indent);
  14294.   if hang_indent>=0 then second_indent:=hang_indent
  14295.   else second_indent:=0;
  14296.   end;
  14297. @ When we come to the following code, we have just encountered the first
  14298. active node~|r| whose |line_number| field contains |l|. Thus we want to
  14299. compute the length of the $l\,$th line of the current paragraph. Furthermore,
  14300. we want to set |old_l| to the last number in the class of line numbers
  14301. equivalent to~|l|.
  14302. @<Compute the new line width@>=
  14303. if l>easy_line then
  14304.   begin line_width:=second_width; old_l:=max_halfword-1;
  14305.   end
  14306. else  begin old_l:=l;
  14307.   if l>last_special_line then line_width:=second_width
  14308.   else if par_shape_ptr=null then line_width:=first_width
  14309.   else line_width:=mem[par_shape_ptr+2*l@,].sc;
  14310.   end
  14311. @ The remaining part of |try_break| deals with the calculation of
  14312. demerits for a break from |r| to |cur_p|.
  14313. The first thing to do is calculate the badness, |b|. This value will always
  14314. be between zero and |inf_bad+1|; the latter value occurs only in the
  14315. case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
  14316. width. In such cases, node |r| will be deactivated.
  14317. We also deactivate node~|r| when a break at~|cur_p| is forced, since future
  14318. breaks must go through a forced break.
  14319. @<Consider the demerits for a line from |r| to |cur_p|...@>=
  14320. begin artificial_demerits:=false;@/
  14321. @^inner loop@>
  14322. shortfall:=line_width-cur_active_width[1]; {we're this much too short}
  14323. if shortfall>0 then
  14324.   @<Set the value of |b| to the badness for stretching the line,
  14325.     and compute the corresponding |fit_class|@>
  14326. else @<Set the value of |b| to the badness for shrinking the line,
  14327.     and compute the corresponding |fit_class|@>;
  14328. if (b>inf_bad)or(pi=eject_penalty) then
  14329.   @<Prepare to deactivate node~|r|, and |goto deactivate| unless
  14330.     there is a reason to consider lines of text from |r| to |cur_p|@>
  14331. else  begin prev_r:=r;
  14332.   if b>threshold then goto continue;
  14333.   node_r_stays_active:=true;
  14334.   end;
  14335. @<Record a new feasible break@>;
  14336. if node_r_stays_active then goto continue; {|prev_r| has been set to |r|}
  14337. deactivate: @<Deactivate node |r|@>;
  14338. @ When a line must stretch, the available stretchability can be found in the
  14339. subarray |cur_active_width[2..5]|, in units of points, fil, fill, and filll.
  14340. The present section is part of \TeX's inner loop, and it is most often performed
  14341. when the badness is infinite; therefore it is worth while to make a quick
  14342. test for large width excess and small stretchability, before calling the
  14343. |badness| subroutine.
  14344. @^inner loop@>
  14345. @<Set the value of |b| to the badness for stretching...@>=
  14346. if (cur_active_width[3]<>0)or(cur_active_width[4]<>0)or@|
  14347.   (cur_active_width[5]<>0) then
  14348.   begin b:=0; fit_class:=decent_fit; {infinite stretch}
  14349.   end
  14350. else  begin if shortfall>7230584 then if cur_active_width[2]<1663497 then
  14351.     begin b:=inf_bad; fit_class:=very_loose_fit; goto done1;
  14352.     end;
  14353.   b:=badness(shortfall,cur_active_width[2]);
  14354.   if b>12 then
  14355.     if b>99 then fit_class:=very_loose_fit
  14356.     else fit_class:=loose_fit
  14357.   else fit_class:=decent_fit;
  14358.   done1:
  14359.   end
  14360. @ Shrinkability is never infinite in a paragraph;
  14361. we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
  14362. @<Set the value of |b| to the badness for shrinking...@>=
  14363. begin if -shortfall>cur_active_width[6] then b:=inf_bad+1
  14364. else b:=badness(-shortfall,cur_active_width[6]);
  14365. if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
  14366. @ During the final pass, we dare not lose all active nodes, lest we lose
  14367. touch with the line breaks already found. The code shown here makes sure
  14368. that such a catastrophe does not happen, by permitting overfull boxes as
  14369. a last resort. This particular part of \TeX\ was a source of several subtle
  14370. bugs before the correct program logic was finally discovered; readers
  14371. who seek to ``improve'' \TeX\ should therefore think thrice before daring
  14372. to make any changes here.
  14373. @^overfull boxes@>
  14374. @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
  14375. begin if final_pass and (minimum_demerits=awful_bad) and@|
  14376.    (link(r)=last_active) and
  14377.    (prev_r=active) then
  14378.   artificial_demerits:=true {set demerits zero, this break is forced}
  14379. else if b>threshold then goto deactivate;
  14380. node_r_stays_active:=false;
  14381. @ When we get to this part of the code, the line from |r| to |cur_p| is
  14382. feasible, its badness is~|b|, and its fitness classification is |fit_class|.
  14383. We don't want to make an active node for this break yet, but we will
  14384. compute the total demerits and record them in the |minimal_demerits| array,
  14385. if such a break is the current champion among all ways to get to |cur_p|
  14386. in a given line-number class and fitness class.
  14387. @<Record a new feasible break@>=
  14388. if artificial_demerits then d:=0
  14389. else @<Compute the demerits, |d|, from |r| to |cur_p|@>;
  14390. @!stat if tracing_paragraphs>0 then
  14391.   @<Print a symbolic description of this feasible break@>;
  14392. tats@;@/
  14393. d:=d+total_demerits(r); {this is the minimum total demerits
  14394.   from the beginning to |cur_p| via |r|}
  14395. if d<=minimal_demerits[fit_class] then
  14396.   begin minimal_demerits[fit_class]:=d;
  14397.   best_place[fit_class]:=break_node(r); best_pl_line[fit_class]:=l;
  14398.   if d<minimum_demerits then minimum_demerits:=d;
  14399.   end
  14400. @ @<Print a symbolic description of this feasible break@>=
  14401. begin if printed_node<>cur_p then
  14402.   @<Print the list between |printed_node| and |cur_p|,
  14403.     then set |printed_node:=cur_p|@>;
  14404. print_nl("@@");
  14405. @.\AT!@>
  14406. if cur_p=null then print_esc("par")
  14407. else if type(cur_p)<>glue_node then
  14408.   begin if type(cur_p)=penalty_node then print_esc("penalty")
  14409.   else if type(cur_p)=disc_node then print_esc("discretionary")
  14410.   else if type(cur_p)=kern_node then print_esc("kern")
  14411.   else print_esc("math");
  14412.   end;
  14413. print(" via @@@@");
  14414. if break_node(r)=null then print_char("0")
  14415. else print_int(serial(break_node(r)));
  14416. print(" b=");
  14417. if b>inf_bad then print_char("*")@+else print_int(b);
  14418. @.*\relax@>
  14419. print(" p="); print_int(pi); print(" d=");
  14420. if artificial_demerits then print_char("*")@+else print_int(d);
  14421. @ @<Print the list between |printed_node| and |cur_p|...@>=
  14422. begin print_nl("");
  14423. if cur_p=null then short_display(link(printed_node))
  14424. else  begin save_link:=link(cur_p);
  14425.   link(cur_p):=null; print_nl(""); short_display(link(printed_node));
  14426.   link(cur_p):=save_link;
  14427.   end;
  14428. printed_node:=cur_p;
  14429. @ When the data for a discretionary break is being displayed, we will have
  14430. printed the |pre_break| and |post_break| lists; we want to skip over the
  14431. third list, so that the discretionary data will not appear twice.  The
  14432. following code is performed at the very end of |try_break|.
  14433. @<Update the value of |printed_node|...@>=
  14434. if cur_p=printed_node then if cur_p<>null then if type(cur_p)=disc_node then
  14435.   begin t:=replace_count(cur_p);
  14436.   while t>0 do
  14437.     begin decr(t); printed_node:=link(printed_node);
  14438.     end;
  14439.   end
  14440. @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
  14441. begin d:=line_penalty+b;
  14442. if abs(d)>=10000 then d:=100000000@+else d:=d*d;
  14443. if pi<>0 then
  14444.   if pi>0 then d:=d+pi*pi
  14445.   else if pi>eject_penalty then d:=d-pi*pi;
  14446. if (break_type=hyphenated)and(type(r)=hyphenated) then
  14447.   if cur_p<>null then d:=d+double_hyphen_demerits
  14448.   else d:=d+final_hyphen_demerits;
  14449. if abs(fit_class-fitness(r))>1 then d:=d+adj_demerits;
  14450. @ When an active node disappears, we must delete an adjacent delta node if the
  14451. active node was at the beginning or the end of the active list, or if it
  14452. was surrounded by delta nodes. We also must preserve the property that
  14453. |cur_active_width| represents the length of material from |link(prev_r)|
  14454. to~|cur_p|.
  14455. @d combine_two_deltas(#)==@|mem[prev_r+#].sc:=mem[prev_r+#].sc+mem[r+#].sc
  14456. @d downdate_width(#)==@|cur_active_width[#]:=cur_active_width[#]-
  14457.   mem[prev_r+#].sc
  14458. @<Deactivate node |r|@>=
  14459. link(prev_r):=link(r); free_node(r,active_node_size);
  14460. if prev_r=active then @<Update the active widths, since the first active
  14461.   node has been deleted@>
  14462. else if type(prev_r)=delta_node then
  14463.   begin r:=link(prev_r);
  14464.   if r=last_active then
  14465.     begin do_all_six(downdate_width);
  14466.     link(prev_prev_r):=last_active;
  14467.     free_node(prev_r,delta_node_size); prev_r:=prev_prev_r;
  14468.     end
  14469.   else if type(r)=delta_node then
  14470.     begin do_all_six(update_width);
  14471.     do_all_six(combine_two_deltas);
  14472.     link(prev_r):=link(r); free_node(r,delta_node_size);
  14473.     end;
  14474.   end
  14475. @ The following code uses the fact that |type(last_active)<>delta_node|. If the
  14476. active list has just become empty, we do not need to update the
  14477. |active_width| array, since it will be initialized when an active
  14478. node is next inserted.
  14479. @d update_active(#)==active_width[#]:=active_width[#]+mem[r+#].sc
  14480. @<Update the active widths,...@>=
  14481. begin r:=link(active);
  14482. if type(r)=delta_node then
  14483.   begin do_all_six(update_active);
  14484.   do_all_six(copy_to_cur_active);
  14485.   link(active):=link(r); free_node(r,delta_node_size);
  14486.   end;
  14487. @* \[39] Breaking paragraphs into lines, continued.
  14488. So far we have gotten a little way into the |line_break| routine, having
  14489. covered its important |try_break| subroutine. Now let's consider the
  14490. rest of the process.
  14491. The main loop of |line_break| traverses the given hlist,
  14492. starting at |link(temp_head)|, and calls |try_break| at each legal
  14493. breakpoint. A variable called |auto_breaking| is set to true except
  14494. within math formulas, since glue nodes are not legal breakpoints when
  14495. they appear in formulas.
  14496. The current node of interest in the hlist is pointed to by |cur_p|. Another
  14497. variable, |prev_p|, is usually one step behind |cur_p|, but the real
  14498. meaning of |prev_p| is this: If |type(cur_p)=glue_node| then |cur_p| is a legal
  14499. breakpoint if and only if |auto_breaking| is true and |prev_p| does not
  14500. point to a glue node, penalty node, explicit kern node, or math node.
  14501. The following declarations provide for a few other local variables that are
  14502. used in special calculations.
  14503. @<Local variables for line breaking@>=
  14504. @!auto_breaking:boolean; {is node |cur_p| outside a formula?}
  14505. @!prev_p:pointer; {helps to determine when glue nodes are breakpoints}
  14506. @!q,@!r,@!s,@!prev_s:pointer; {miscellaneous nodes of temporary interest}
  14507. @!f:internal_font_number; {used when calculating character widths}
  14508. @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
  14509. thrice per call of |line_break|, since it is actually a pass over the
  14510. entire paragraph.
  14511. @<Find optimal breakpoints@>=
  14512. threshold:=pretolerance;
  14513. if threshold>=0 then
  14514.   begin @!stat if tracing_paragraphs>0 then
  14515.     begin begin_diagnostic; print_nl("@@firstpass");@+end;@;@+tats@;@/
  14516.   second_pass:=false; final_pass:=false;
  14517.   end
  14518. else  begin threshold:=tolerance; second_pass:=true;
  14519.   final_pass:=(emergency_stretch<=0);
  14520.   @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
  14521.   end;
  14522. loop@+  begin if threshold>inf_bad then threshold:=inf_bad;
  14523.   if second_pass then @<Initialize for hyphenating a paragraph@>;
  14524.   @<Create an active breakpoint representing the beginning of the paragraph@>;
  14525.   cur_p:=link(temp_head); auto_breaking:=true;@/
  14526.   prev_p:=cur_p; {glue at beginning is not a legal breakpoint}
  14527.   while (cur_p<>null)and(link(active)<>last_active) do
  14528.     @<Call |try_break| if |cur_p| is a legal breakpoint;
  14529.     on the second pass, also try to hyphenate the next
  14530.     word, if |cur_p| is a glue node;
  14531.     then advance |cur_p| to the next node of the paragraph
  14532.     that could possibly be a legal breakpoint@>;
  14533.   if cur_p=null then
  14534.     @<Try the final line break at the end of the paragraph,
  14535.     and |goto done| if the desired breakpoints have been found@>;
  14536.   @<Clean up the memory by removing the break nodes@>;
  14537.   if not second_pass then
  14538.     begin@!stat if tracing_paragraphs>0 then print_nl("@@secondpass");@;@+tats@/
  14539.     threshold:=tolerance; second_pass:=true; final_pass:=(emergency_stretch<=0);
  14540.     end {if at first you don't succeed, \dots}
  14541.   else begin @!stat if tracing_paragraphs>0 then
  14542.       print_nl("@@emergencypass");@;@+tats@/
  14543.     background[2]:=background[2]+emergency_stretch; final_pass:=true;
  14544.     end;
  14545.   end;
  14546. done: @!stat if tracing_paragraphs>0 then
  14547.   begin end_diagnostic(true); normalize_selector;
  14548.   end;@+tats@/
  14549. @ The active node that represents the starting point does not need a
  14550. corresponding passive node.
  14551. @d store_background(#)==active_width[#]:=background[#]
  14552. @<Create an active breakpoint representing the beginning of the paragraph@>=
  14553. q:=get_node(active_node_size);
  14554. type(q):=unhyphenated; fitness(q):=decent_fit;
  14555. link(q):=last_active; break_node(q):=null;
  14556. line_number(q):=prev_graf+1; total_demerits(q):=0; link(active):=q;
  14557. do_all_six(store_background);@/
  14558. passive:=null; printed_node:=temp_head; pass_number:=0;
  14559. font_in_short_display:=null_font
  14560. @ @<Clean...@>=
  14561. q:=link(active);
  14562. while q<>last_active do
  14563.   begin cur_p:=link(q);
  14564.   if type(q)=delta_node then free_node(q,delta_node_size)
  14565.   else free_node(q,active_node_size);
  14566.   q:=cur_p;
  14567.   end;
  14568. q:=passive;
  14569. while q<>null do
  14570.   begin cur_p:=link(q);
  14571.   free_node(q,passive_node_size);
  14572.   q:=cur_p;
  14573.   end
  14574. @ Here is the main switch in the |line_break| routine, where legal breaks
  14575. are determined. As we move through the hlist, we need to keep the |active_width|
  14576. array up to date, so that the badness of individual lines is readily calculated
  14577. by |try_break|. It is convenient to use the short name |act_width| for
  14578. the component of active width that represents real width as opposed to glue.
  14579. @d act_width==active_width[1] {length from first active node to current node}
  14580. @d kern_break==begin if not is_char_node(link(cur_p)) and auto_breaking then
  14581.     if type(link(cur_p))=glue_node then try_break(0,unhyphenated);
  14582.   act_width:=act_width+width(cur_p);
  14583.   end
  14584. @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
  14585. begin if is_char_node(cur_p) then
  14586.   @<Advance \(c)|cur_p| to the node following the present
  14587.     string of characters@>;
  14588. case type(cur_p) of
  14589. hlist_node,vlist_node,rule_node: act_width:=act_width+width(cur_p);
  14590. whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>;
  14591. glue_node: begin @<If node |cur_p| is a legal breakpoint, call |try_break|;
  14592.   then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
  14593.   if second_pass and auto_breaking then
  14594.     @<Try to hyphenate the following word@>;
  14595.   end;
  14596. kern_node: if subtype(cur_p)=explicit then kern_break
  14597.   else act_width:=act_width+width(cur_p);
  14598. ligature_node: begin f:=font(lig_char(cur_p));
  14599.   act_width:=act_width+char_width(f)(char_info(f)(character(lig_char(cur_p))));
  14600.   end;
  14601. disc_node: @<Try to break after a discretionary fragment, then |goto done5|@>;
  14602. math_node: begin auto_breaking:=(subtype(cur_p)=after); kern_break;
  14603.   end;
  14604. penalty_node: try_break(penalty(cur_p),unhyphenated);
  14605. mark_node,ins_node,adjust_node: do_nothing;
  14606. othercases confusion("paragraph")
  14607. @:this can't happen paragraph}{\quad paragraph@>
  14608. endcases;@/
  14609. prev_p:=cur_p; cur_p:=link(cur_p);
  14610. done5:end
  14611. @ The code that passes over the characters of words in a paragraph is
  14612. part of \TeX's inner loop, so it has been streamlined for speed. We use
  14613. the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
  14614. it is therefore unnecessary to check if |link(cur_p)=null| when |cur_p| is a
  14615. character node.
  14616. @^inner loop@>
  14617. @<Advance \(c)|cur_p| to the node following the present string...@>=
  14618. begin prev_p:=cur_p;
  14619. repeat f:=font(cur_p);
  14620. act_width:=act_width+char_width(f)(char_info(f)(character(cur_p)));
  14621. cur_p:=link(cur_p);
  14622. until not is_char_node(cur_p);
  14623. @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
  14624. a breakpoint is legal at |cur_p|, as explained above.
  14625. @<If node |cur_p| is a legal breakpoint, call...@>=
  14626. if auto_breaking then
  14627.   begin if is_char_node(prev_p) then try_break(0,unhyphenated)
  14628.   else if precedes_break(prev_p) then try_break(0,unhyphenated)
  14629.   else if (type(prev_p)=kern_node)and(subtype(prev_p)<>explicit) then
  14630.     try_break(0,unhyphenated);
  14631.   end;
  14632. check_shrinkage(glue_ptr(cur_p)); q:=glue_ptr(cur_p);
  14633. act_width:=act_width+width(q);@|
  14634. active_width[2+stretch_order(q)]:=@|
  14635.   active_width[2+stretch_order(q)]+stretch(q);@/
  14636. active_width[6]:=active_width[6]+shrink(q)
  14637. @ The following code knows that discretionary texts contain
  14638. only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
  14639. @<Try to break after a discretionary fragment...@>=
  14640. begin s:=pre_break(cur_p); disc_width:=0;
  14641. if s=null then try_break(ex_hyphen_penalty,hyphenated)
  14642. else  begin repeat @<Add the width of node |s| to |disc_width|@>;
  14643.     s:=link(s);
  14644.   until s=null;
  14645.   act_width:=act_width+disc_width;
  14646.   try_break(hyphen_penalty,hyphenated);
  14647.   act_width:=act_width-disc_width;
  14648.   end;
  14649. r:=replace_count(cur_p); s:=link(cur_p);
  14650. while r>0 do
  14651.   begin @<Add the width of node |s| to |act_width|@>;
  14652.   decr(r); s:=link(s);
  14653.   end;
  14654. prev_p:=cur_p; cur_p:=s; goto done5;
  14655. @ @<Add the width of node |s| to |disc_width|@>=
  14656. if is_char_node(s) then
  14657.   begin f:=font(s);
  14658.   disc_width:=disc_width+char_width(f)(char_info(f)(character(s)));
  14659.   end
  14660. else  case type(s) of
  14661.   ligature_node: begin f:=font(lig_char(s));
  14662.     disc_width:=disc_width+
  14663.       char_width(f)(char_info(f)(character(lig_char(s))));
  14664.     end;
  14665.   hlist_node,vlist_node,rule_node,kern_node:
  14666.     disc_width:=disc_width+width(s);
  14667.   othercases confusion("disc3")
  14668. @:this can't happen disc3}{\quad disc3@>
  14669.   endcases
  14670. @ @<Add the width of node |s| to |act_width|@>=
  14671. if is_char_node(s) then
  14672.   begin f:=font(s);
  14673.   act_width:=act_width+char_width(f)(char_info(f)(character(s)));
  14674.   end
  14675. else  case type(s) of
  14676.   ligature_node: begin f:=font(lig_char(s));
  14677.     act_width:=act_width+
  14678.       char_width(f)(char_info(f)(character(lig_char(s))));
  14679.     end;
  14680.   hlist_node,vlist_node,rule_node,kern_node:
  14681.     act_width:=act_width+width(s);
  14682.   othercases confusion("disc4")
  14683. @:this can't happen disc4}{\quad disc4@>
  14684.   endcases
  14685. @ The forced line break at the paragraph's end will reduce the list of
  14686. breakpoints so that all active nodes represent breaks at |cur_p=null|.
  14687. On the first pass, we insist on finding an active node that has the
  14688. correct ``looseness.'' On the final pass, there will be at least one active
  14689. node, and we will match the desired looseness as well as we can.
  14690. The global variable |best_bet| will be set to the active node for the best
  14691. way to break the paragraph, and a few other variables are used to
  14692. help determine what is best.
  14693. @<Glob...@>=
  14694. @!best_bet:pointer; {use this passive node and its predecessors}
  14695. @!fewest_demerits:integer; {the demerits associated with |best_bet|}
  14696. @!best_line:halfword; {line number following the last line of the new paragraph}
  14697. @!actual_looseness:integer; {the difference between |line_number(best_bet)|
  14698.   and the optimum |best_line|}
  14699. @!line_diff:integer; {the difference between the current line number and
  14700.   the optimum |best_line|}
  14701. @ @<Try the final line break at the end of the paragraph...@>=
  14702. begin try_break(eject_penalty,hyphenated);
  14703. if link(active)<>last_active then
  14704.   begin @<Find an active node with fewest demerits@>;
  14705.   if looseness=0 then goto done;
  14706.   @<Find the best active node for the desired looseness@>;
  14707.   if (actual_looseness=looseness)or final_pass then goto done;
  14708.   end;
  14709. @ @<Find an active node...@>=
  14710. r:=link(active); fewest_demerits:=awful_bad;
  14711. repeat if type(r)<>delta_node then if total_demerits(r)<fewest_demerits then
  14712.   begin fewest_demerits:=total_demerits(r); best_bet:=r;
  14713.   end;
  14714. r:=link(r);
  14715. until r=last_active;
  14716. best_line:=line_number(best_bet)
  14717. @ The adjustment for a desired looseness is a slightly more complicated
  14718. version of the loop just considered. Note that if a paragraph is broken
  14719. into segments by displayed equations, each segment will be subject to the
  14720. looseness calculation, independently of the other segments.
  14721. @<Find the best active node...@>=
  14722. begin r:=link(active); actual_looseness:=0;
  14723. repeat if type(r)<>delta_node then
  14724.   begin line_diff:=line_number(r)-best_line;
  14725.   if ((line_diff<actual_looseness)and(looseness<=line_diff))or@|
  14726.   ((line_diff>actual_looseness)and(looseness>=line_diff)) then
  14727.     begin best_bet:=r; actual_looseness:=line_diff;
  14728.     fewest_demerits:=total_demerits(r);
  14729.     end
  14730.   else if (line_diff=actual_looseness)and@|
  14731.     (total_demerits(r)<fewest_demerits) then
  14732.     begin best_bet:=r; fewest_demerits:=total_demerits(r);
  14733.     end;
  14734.   end;
  14735. r:=link(r);
  14736. until r=last_active;
  14737. best_line:=line_number(best_bet);
  14738. @ Once the best sequence of breakpoints has been found (hurray), we call on the
  14739. procedure |post_line_break| to finish the remainder of the work.
  14740. (By introducing this subprocedure, we are able to keep |line_break|
  14741. from getting extremely long.)
  14742. @<Break the paragraph at the chosen...@>=
  14743. post_line_break(final_widow_penalty)
  14744. @ The total number of lines that will be set by |post_line_break|
  14745. is |best_line-prev_graf-1|. The last breakpoint is specified by
  14746. |break_node(best_bet)|, and this passive node points to the other breakpoints
  14747. via the |prev_break| links. The finishing-up phase starts by linking the
  14748. relevant passive nodes in forward order, changing |prev_break| to
  14749. |next_break|. (The |next_break| fields actually reside in the same memory
  14750. space as the |prev_break| fields did, but we give them a new name because
  14751. of their new significance.) Then the lines are justified, one by one.
  14752. @d next_break==prev_break {new name for |prev_break| after links are reversed}
  14753. @<Declare subprocedures for |line_break|@>=
  14754. procedure post_line_break(@!final_widow_penalty:integer);
  14755. label done,done1;
  14756. var q,@!r,@!s:pointer; {temporary registers for list manipulation}
  14757. @!disc_break:boolean; {was the current break at a discretionary node?}
  14758. @!post_disc_break:boolean; {and did it have a nonempty post-break part?}
  14759. @!cur_width:scaled; {width of line number |cur_line|}
  14760. @!cur_indent:scaled; {left margin of line number |cur_line|}
  14761. @!t:quarterword; {used for replacement counts in discretionary nodes}
  14762. @!pen:integer; {use when calculating penalties between lines}
  14763. @!cur_line: halfword; {the current line number being justified}
  14764. begin @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
  14765.   first breakpoint@>;
  14766. cur_line:=prev_graf+1;
  14767. repeat @<Justify the line ending at breakpoint |cur_p|, and append it to the
  14768.   current vertical list, together with associated penalties and other
  14769.   insertions@>;
  14770. incr(cur_line); cur_p:=next_break(cur_p);
  14771. if cur_p<>null then if not post_disc_break then
  14772.   @<Prune unwanted nodes at the beginning of the next line@>;
  14773. until cur_p=null;
  14774. if (cur_line<>best_line)or(link(temp_head)<>null) then
  14775.   confusion("line breaking");
  14776. @:this can't happen line breaking}{\quad line breaking@>
  14777. prev_graf:=best_line-1;
  14778. @ The job of reversing links in a list is conveniently regarded as the job
  14779. of taking items off one stack and putting them on another. In this case we
  14780. take them off a stack pointed to by |q| and having |prev_break| fields;
  14781. we put them on a stack pointed to by |cur_p| and having |next_break| fields.
  14782. Node |r| is the passive node being moved from stack to stack.
  14783. @<Reverse the links of the relevant passive nodes...@>=
  14784. q:=break_node(best_bet); cur_p:=null;
  14785. repeat r:=q; q:=prev_break(q); next_break(r):=cur_p; cur_p:=r;
  14786. until q=null
  14787. @ Glue and penalty and kern and math nodes are deleted at the beginning of
  14788. a line, except in the anomalous case that the node to be deleted is actually
  14789. one of the chosen breakpoints. Otherwise
  14790. the pruning done here is designed to match
  14791. the lookahead computation in |try_break|, where the |break_width| values
  14792. are computed for non-discretionary breakpoints.
  14793. @<Prune unwanted nodes at the beginning of the next line@>=
  14794. begin r:=temp_head;
  14795. loop@+  begin q:=link(r);
  14796.   if q=cur_break(cur_p) then goto done1;
  14797.     {|cur_break(cur_p)| is the next breakpoint}
  14798.   {now |q| cannot be |null|}
  14799.   if is_char_node(q) then goto done1;
  14800.   if non_discardable(q) then goto done1;
  14801.   if type(q)=kern_node then if subtype(q)<>explicit then goto done1;
  14802.   r:=q; {now |type(q)=glue_node|, |kern_node|, |math_node| or |penalty_node|}
  14803.   end;
  14804. done1: if r<>temp_head then
  14805.   begin link(r):=null; flush_node_list(link(temp_head));
  14806.   link(temp_head):=q;
  14807.   end;
  14808. @ The current line to be justified appears in a horizontal list starting
  14809. at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
  14810. a glue node, we reset the glue to equal the |right_skip| glue; otherwise
  14811. we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
  14812. discretionary node, we modify the list so that the discretionary break
  14813. is compulsory, and we set |disc_break| to |true|. We also append
  14814. the |left_skip| glue at the left of the line, unless it is zero.
  14815. @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
  14816. @<Modify the end of the line to reflect the nature of the break and to include
  14817.   \.{\\rightskip}; also set the proper value of |disc_break|@>;
  14818. @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
  14819. @<Call the packaging subroutine, setting |just_box| to the justified box@>;
  14820. @<Append the new box to the current vertical list, followed by the list of
  14821.   special nodes taken out of the box by the packager@>;
  14822. @<Append a penalty node, if a nonzero penalty is appropriate@>
  14823. @ At the end of the following code, |q| will point to the final node on the
  14824. list about to be justified.
  14825. @<Modify the end of the line...@>=
  14826. q:=cur_break(cur_p); disc_break:=false; post_disc_break:=false;
  14827. if q<>null then {|q| cannot be a |char_node|}
  14828.   if type(q)=glue_node then
  14829.     begin delete_glue_ref(glue_ptr(q));
  14830.     glue_ptr(q):=right_skip;
  14831.     subtype(q):=right_skip_code+1; add_glue_ref(right_skip);
  14832.     goto done;
  14833.     end
  14834.   else  begin if type(q)=disc_node then
  14835.       @<Change discretionary to compulsory and set
  14836.         |disc_break:=true|@>
  14837.     else if (type(q)=math_node)or(type(q)=kern_node) then width(q):=0;
  14838.     end
  14839. else  begin q:=temp_head;
  14840.   while link(q)<>null do q:=link(q);
  14841.   end;
  14842. @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
  14843. done:
  14844. @ @<Change discretionary to compulsory...@>=
  14845. begin t:=replace_count(q);
  14846. @<Destroy the |t| nodes following |q|, and
  14847.    make |r| point to the following node@>;
  14848. if post_break(q)<>null then @<Transplant the post-break list@>;
  14849. if pre_break(q)<>null then @<Transplant the pre-break list@>;
  14850. link(q):=r; disc_break:=true;
  14851. @ @<Destroy the |t| nodes following |q|...@>=
  14852. if t=0 then r:=link(q)
  14853. else  begin r:=q;
  14854.   while t>1 do
  14855.     begin r:=link(r); decr(t);
  14856.     end;
  14857.   s:=link(r);
  14858.   r:=link(s); link(s):=null;
  14859.   flush_node_list(link(q)); replace_count(q):=0;
  14860.   end
  14861. @ We move the post-break list from inside node |q| to the main list by
  14862. re\-attaching it just before the present node |r|, then resetting |r|.
  14863. @<Transplant the post-break list@>=
  14864. begin s:=post_break(q);
  14865. while link(s)<>null do s:=link(s);
  14866. link(s):=r; r:=post_break(q); post_break(q):=null; post_disc_break:=true;
  14867. @ We move the pre-break list from inside node |q| to the main list by
  14868. re\-attaching it just after the present node |q|, then resetting |q|.
  14869. @<Transplant the pre-break list@>=
  14870. begin s:=pre_break(q); link(q):=s;
  14871. while link(s)<>null do s:=link(s);
  14872. pre_break(q):=null; q:=s;
  14873. @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
  14874. r:=new_param_glue(right_skip_code); link(r):=link(q); link(q):=r; q:=r
  14875. @ The following code begins with |q| at the end of the list to be
  14876. justified. It ends with |q| at the beginning of that list, and with
  14877. |link(temp_head)| pointing to the remainder of the paragraph, if any.
  14878. @<Put the \(l)\.{\\leftskip} glue at the left...@>=
  14879. r:=link(q); link(q):=null; q:=link(temp_head); link(temp_head):=r;
  14880. if left_skip<>zero_glue then
  14881.   begin r:=new_param_glue(left_skip_code);
  14882.   link(r):=q; q:=r;
  14883.   end
  14884. @ @<Append the new box to the current vertical list...@>=
  14885. append_to_vlist(just_box);
  14886. if adjust_head<>adjust_tail then
  14887.   begin link(tail):=link(adjust_head); tail:=adjust_tail;
  14888.    end;
  14889. adjust_tail:=null
  14890. @ Now |q| points to the hlist that represents the current line of the
  14891. paragraph. We need to compute the appropriate line width, pack the
  14892. line into a box of this size, and shift the box by the appropriate
  14893. amount of indentation.
  14894. @<Call the packaging subroutine...@>=
  14895. if cur_line>last_special_line then
  14896.   begin cur_width:=second_width; cur_indent:=second_indent;
  14897.   end
  14898. else if par_shape_ptr=null then
  14899.   begin cur_width:=first_width; cur_indent:=first_indent;
  14900.   end
  14901. else  begin cur_width:=mem[par_shape_ptr+2*cur_line].sc;
  14902.   cur_indent:=mem[par_shape_ptr+2*cur_line-1].sc;
  14903.   end;
  14904. adjust_tail:=adjust_head; just_box:=hpack(q,cur_width,exactly);
  14905. shift_amount(just_box):=cur_indent
  14906. @ Penalties between the lines of a paragraph come from club and widow lines,
  14907. from the |inter_line_penalty| parameter, and from lines that end at
  14908. discretionary breaks.  Breaking between lines of a two-line paragraph gets
  14909. both club-line and widow-line penalties. The local variable |pen| will
  14910. be set to the sum of all relevant penalties for the current line, except
  14911. that the final line is never penalized.
  14912. @<Append a penalty node, if a nonzero penalty is appropriate@>=
  14913. if cur_line+1<>best_line then
  14914.   begin pen:=inter_line_penalty;
  14915.   if cur_line=prev_graf+1 then pen:=pen+club_penalty;
  14916.   if cur_line+2=best_line then pen:=pen+final_widow_penalty;
  14917.   if disc_break then pen:=pen+broken_penalty;
  14918.   if pen<>0 then
  14919.     begin r:=new_penalty(pen);
  14920.     link(tail):=r; tail:=r;
  14921.     end;
  14922.   end
  14923. @* \[40] Pre-hyphenation.
  14924. When the line-breaking routine is unable to find a feasible sequence of
  14925. breakpoints, it makes a second pass over the paragraph, attempting to
  14926. hyphenate the hyphenatable words. The goal of hyphenation is to insert
  14927. discretionary material into the paragraph so that there are more
  14928. potential places to break.
  14929. The general rules for hyphenation are somewhat complex and technical,
  14930. because we want to be able to hyphenate words that are preceded or
  14931. followed by punctuation marks, and because we want the rules to work
  14932. for languages other than English. We also must contend with the fact
  14933. that hyphens might radically alter the ligature and kerning structure
  14934. of a word.
  14935. A sequence of characters will be considered for hyphenation only if it
  14936. belongs to a ``potentially hyphenatable part'' of the current paragraph.
  14937. This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
  14938. $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
  14939. implicit kern nodes, and $p_m$ is a glue or penalty or insertion or adjust
  14940. or mark or whatsit or explicit kern node.  (Therefore hyphenation is
  14941. disabled by boxes, math formulas, and discretionary nodes already inserted
  14942. by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
  14943. expanded into the original non-ligature characters; the kern nodes and
  14944. whatsits are ignored. Each character |c| is now classified as either a
  14945. nonletter (if |lc_code(c)=0|), a lowercase letter (if
  14946. |lc_code(c)=c|), or an uppercase letter (otherwise); an uppercase letter
  14947. is treated as if it were |lc_code(c)| for purposes of hyphenation. The
  14948. characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
  14949. $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
  14950. nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
  14951. terminating node $p_m$. All characters that do not have the same font as
  14952. $c_1$ will be treated as nonletters. The |hyphen_char| for that font
  14953. must be between 0 and 255, otherwise hyphenation will not be attempted.
  14954. \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
  14955. possible; however, |n| must be less than 64, so a character that would
  14956. otherwise be $c_{64}$ is effectively not a letter. Furthermore $c_n$ must
  14957. not be in the middle of a ligature.  In this way we obtain a string of
  14958. letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
  14959. |1<=a<=b+1<=m|. If |n>=l_hyf+r_hyf|, this string qualifies for hyphenation;
  14960. however, |uc_hyph| must be positive, if $c_1$ is uppercase.
  14961. The hyphenation process takes place in three stages. First, the candidate
  14962. sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
  14963. are determined by referring to hyphenation tables; and finally, the nodes
  14964. $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
  14965. discretionary breaks found.
  14966. Fortunately, we do not have to do all this calculation very often, because
  14967. of the way it has been taken out of \TeX's inner loop. For example, when
  14968. the second edition of the author's 700-page book {\sl Seminumerical
  14969. Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
  14970. @^Knuth, Donald Ervin@>
  14971. tried per paragraph, since the line breaking algorithm needed to use two
  14972. passes on only about 5 per cent of the paragraphs.
  14973. @<Initialize for hyphenating...@>=
  14974. begin @!init if trie_not_ready then init_trie;@+tini@;@/
  14975. cur_lang:=init_cur_lang; l_hyf:=init_l_hyf; r_hyf:=init_r_hyf;
  14976. @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
  14977. into an array called |hc|; the number |n| is placed into |hn|; pointers to
  14978. nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
  14979. |ha| and |hb|; and the font number is placed into |hf|.
  14980. @<Glob...@>=
  14981. @!hc:array[0..65] of 0..256; {word to be hyphenated}
  14982. @!hn:small_number; {the number of positions occupied in |hc|}
  14983. @!ha,@!hb:pointer; {nodes |ha..hb| should be replaced by the hyphenated result}
  14984. @!hf:internal_font_number; {font number of the letters in |hc|}
  14985. @!hu:array[0..63] of 0..256; {like |hc|, before conversion to lowercase}
  14986. @!hyf_char:integer; {hyphen character of the relevant font}
  14987. @!cur_lang,@!init_cur_lang:ASCII_code; {current hyphenation table of interest}
  14988. @!l_hyf,@!r_hyf,@!init_l_hyf,@!init_r_hyf:integer; {limits on fragment sizes}
  14989. @!hyf_bchar:halfword; {boundary character after $c_n$}
  14990. @ Hyphenation routines need a few more local variables.
  14991. @<Local variables for line...@>=
  14992. @!j:small_number; {an index into |hc| or |hu|}
  14993. @!c:0..255; {character being considered for hyphenation}
  14994. @ When the following code is activated, the |line_break| procedure is in its
  14995. second pass, and |cur_p| points to a glue node.
  14996. @<Try to hyphenate...@>=
  14997. begin prev_s:=cur_p; s:=link(prev_s);
  14998. if s<>null then
  14999.   begin @<Skip to node |ha|, or |goto done1| if no hyphenation
  15000.     should be attempted@>;
  15001.   if l_hyf+r_hyf>63 then goto done1;
  15002.   @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
  15003.   @<Check that the nodes following |hb| permit hyphenation and that at least
  15004.     |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
  15005.   hyphenate;
  15006.   end;
  15007. done1: end
  15008. @ @<Declare subprocedures for |line_break|@>=
  15009. @t\4@>@<Declare the function called |reconstitute|@>
  15010. procedure hyphenate;
  15011. label common_ending,done,found,found1,found2,not_found,exit;
  15012. var @<Local variables for hyphenation@>@;
  15013. begin @<Find hyphen locations for the word in |hc|, or |return|@>;
  15014. @<If no hyphens were found, |return|@>;
  15015. @<Replace nodes |ha..hb| by a sequence of nodes that includes
  15016.   the discretionary hyphens@>;
  15017. exit:end;
  15018. @ The first thing we need to do is find the node |ha| just before the
  15019. first letter.
  15020. @<Skip to node |ha|, or |goto done1|...@>=
  15021. loop@+  begin if is_char_node(s) then
  15022.     begin c:=qo(character(s)); hf:=font(s);
  15023.     end
  15024.   else if type(s)=ligature_node then
  15025.     if lig_ptr(s)=null then goto continue
  15026.     else begin q:=lig_ptr(s); c:=qo(character(q)); hf:=font(q);
  15027.       end
  15028.   else if (type(s)=kern_node)and(subtype(s)=normal) then goto continue
  15029.   else if type(s)=whatsit_node then
  15030.     begin @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
  15031.     goto continue;
  15032.     end
  15033.   else goto done1;
  15034.   if lc_code(c)<>0 then
  15035.     if (lc_code(c)=c)or(uc_hyph>0) then goto done2
  15036.     else goto done1;
  15037. continue: prev_s:=s; s:=link(prev_s);
  15038.   end;
  15039. done2: hyf_char:=hyphen_char[hf];
  15040. if hyf_char<0 then goto done1;
  15041. if hyf_char>255 then goto done1;
  15042. ha:=prev_s
  15043. @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
  15044. @<Skip to node |hb|, putting letters...@>=
  15045. hn:=0;
  15046. loop@+  begin if is_char_node(s) then
  15047.     begin if font(s)<>hf then goto done3;
  15048.     hyf_bchar:=character(s); c:=qo(hyf_bchar);
  15049.     if lc_code(c)=0 then goto done3;
  15050.     if hn=63 then goto done3;
  15051.     hb:=s; incr(hn); hu[hn]:=c; hc[hn]:=lc_code(c); hyf_bchar:=non_char;
  15052.     end
  15053.   else if type(s)=ligature_node then
  15054.     @<Move the characters of a ligature node to |hu| and |hc|;
  15055.       but |goto done3| if they are not all letters@>
  15056.   else if (type(s)=kern_node)and(subtype(s)=normal) then
  15057.     begin hb:=s;
  15058.     hyf_bchar:=font_bchar[hf];
  15059.     end
  15060.   else goto done3;
  15061.   s:=link(s);
  15062.   end;
  15063. done3:
  15064. @ We let |j| be the index of the character being stored when a ligature node
  15065. is being expanded, since we do not want to advance |hn| until we are sure
  15066. that the entire ligature consists of letters. Note that it is possible
  15067. to get to |done3| with |hn=0| and |hb| not set to any value.
  15068. @<Move the characters of a ligature node to |hu| and |hc|...@>=
  15069. begin if font(lig_char(s))<>hf then goto done3;
  15070. j:=hn; q:=lig_ptr(s);@+if q>null then hyf_bchar:=character(q);
  15071. while q>null do
  15072.   begin c:=qo(character(q));
  15073.   if lc_code(c)=0 then goto done3;
  15074.   if j=63 then goto done3;
  15075.   incr(j); hu[j]:=c; hc[j]:=lc_code(c);@/
  15076.   q:=link(q);
  15077.   end;
  15078. hb:=s; hn:=j;
  15079. if odd(subtype(s)) then hyf_bchar:=font_bchar[hf]@+else hyf_bchar:=non_char;
  15080. @ @<Check that the nodes following |hb| permit hyphenation...@>=
  15081. if hn<l_hyf+r_hyf then goto done1; {|l_hyf| and |r_hyf| are |>=1|}
  15082. loop@+  begin if not(is_char_node(s)) then
  15083.     case type(s) of
  15084.     ligature_node: do_nothing;
  15085.     kern_node: if subtype(s)<>normal then goto done4;
  15086.     whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node:
  15087.       goto done4;
  15088.     othercases goto done1
  15089.     endcases;
  15090.   s:=link(s);
  15091.   end;
  15092. done4:
  15093. @* \[41] Post-hyphenation.
  15094. If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
  15095. procedure will set |hyf[j]| to some small odd number. But before we look
  15096. at \TeX's hyphenation procedure, which is independent of the rest of the
  15097. line-breaking algorithm, let us consider what we will do with the hyphens
  15098. it finds, since it is better to work on this part of the program before
  15099. forgetting what |ha| and |hb|, etc., are all about.
  15100. @<Glob...@>=
  15101. @!hyf:array [0..64] of 0..9; {odd values indicate discretionary hyphens}
  15102. @!init_list:pointer; {list of punctuation characters preceding the word}
  15103. @!init_lig:boolean; {does |init_list| represent a ligature?}
  15104. @!init_lft:boolean; {if so, did the ligature involve a left boundary?}
  15105. @ @<Local variables for hyphenation@>=
  15106. @!i,@!j,@!l:0..65; {indices into |hc| or |hu|}
  15107. @!q,@!r,@!s:pointer; {temporary registers for list manipulation}
  15108. @!bchar:halfword; {right boundary character of hyphenated word, or |non_char|}
  15109. @ \TeX\ will never insert a hyphen that has fewer than
  15110. \.{\\lefthyphenmin} letters before it or fewer than
  15111. \.{\\righthyphenmin} after it; hence, a short word has
  15112. comparatively little chance of being hyphenated. If no hyphens have
  15113. been found, we can save time by not having to make any changes to the
  15114. paragraph.
  15115. @<If no hyphens were found, |return|@>=
  15116. for j:=l_hyf to hn-r_hyf do if odd(hyf[j]) then goto found1;
  15117. return;
  15118. found1:
  15119. @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
  15120. subsequence of nodes between |ha| and~|hb|. An attempt is made to
  15121. preserve the effect that implicit boundary characters and punctuation marks
  15122. had on ligatures inside the hyphenated word, by storing a left boundary or
  15123. preceding character in |hu[0]| and by storing a possible right boundary
  15124. in |bchar|. We set |j:=0| if |hu[0]| is to be part of the reconstruction;
  15125. otherwise |j:=1|.
  15126. The variable |s| will point to the tail of the current hlist, and
  15127. |q| will point to the node following |hb|, so that
  15128. things can be hooked up after we reconstitute the hyphenated word.
  15129. @<Replace nodes |ha..hb| by a sequence of nodes...@>=
  15130. q:=link(hb); link(hb):=null; r:=link(ha); link(ha):=null; bchar:=hyf_bchar;
  15131. if is_char_node(ha) then
  15132.   if font(ha)<>hf then goto found2
  15133.   else begin init_list:=ha; init_lig:=false; hu[0]:=qo(character(ha));
  15134.     end
  15135. else if type(ha)=ligature_node then
  15136.   if font(lig_char(ha))<>hf then goto found2
  15137.   else begin init_list:=lig_ptr(ha); init_lig:=true; init_lft:=(subtype(ha)>1);
  15138.     hu[0]:=qo(character(lig_char(ha)));
  15139.     if init_list=null then if init_lft then
  15140.       begin hu[0]:=256; init_lig:=false;
  15141.       end; {in this case a ligature will be reconstructed from scratch}
  15142.     free_node(ha,small_node_size);
  15143.     end
  15144. else begin {no punctuation found; look for left boundary}
  15145.   if not is_char_node(r) then if type(r)=ligature_node then
  15146.    if subtype(r)>1 then goto found2;
  15147.   j:=1; s:=ha; init_list:=null; goto common_ending;
  15148.   end;
  15149. s:=cur_p; {we have |cur_p<>ha| because |type(cur_p)=glue_node|}
  15150. while link(s)<>ha do s:=link(s);
  15151. j:=0; goto common_ending;
  15152. found2: s:=ha; j:=0; hu[0]:=256; init_lig:=false; init_list:=null;
  15153. common_ending: flush_node_list(r);
  15154. @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
  15155. flush_list(init_list)
  15156. @ We must now face the fact that the battle is not over, even though the
  15157. {\def\!{\kern-1pt}%
  15158. hyphens have been found: The process of reconstituting a word can be nontrivial
  15159. because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
  15160. discusses the difficulties of the word ``difficult'', and
  15161. the discretionary material surrounding a
  15162. hyphen can be considerably more complex than that. Suppose
  15163. \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
  15164. \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
  15165. between \.b and \.c, the two patterns with and without hyphenation are
  15166. $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
  15167. Thus the insertion of a hyphen might cause effects to ripple arbitrarily
  15168. far into the rest of the word. A further complication arises if additional
  15169. hyphens appear together with such rippling, e.g., if the word in the
  15170. example just given could also be hyphenated between \.c and \.d; \TeX\
  15171. avoids this by simply ignoring the additional hyphens in such weird cases.}
  15172. Still further complications arise in the presence of ligatures that do not
  15173. delete the original characters. When punctuation precedes the word being
  15174. hyphenated, \TeX's method is not perfect under all possible scenarios,
  15175. because punctuation marks and letters can propagate information back and forth.
  15176. For example, suppose the original pre-hyphenation pair
  15177. \.{*a} changes to \.{*y} via a \.{\?=:} ligature, which changes to \.{xy}
  15178. via a \.{=:\?} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
  15179. procedure isn't smart enough to obtain \.{xy} again. In such cases the
  15180. font designer should include a ligature that goes from \.{xa} to \.{xy}.
  15181. @ The processing is facilitated by a subroutine called |reconstitute|. Given
  15182. a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
  15183. such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
  15184. has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
  15185. where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
  15186. kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
  15187. For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
  15188. ligature and a kern between `fl' and `y', then $m=2$, $y=2$, and $y_1$ will
  15189. be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
  15190. In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
  15191. simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
  15192. $x_{m+1}\ldots x_n$ until the entire translation has been found.
  15193. The |reconstitute| function returns the integer $m$ and puts the nodes
  15194. $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
  15195. getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
  15196. we consider $x_j$ to be an implicit left boundary character; in this
  15197. case |j| must be strictly less than~|n|. There is a
  15198. parameter |bchar|, which is either 256 or an implicit right boundary character
  15199. assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
  15200. explicitly examined, but the algorithm imagines that |bchar| is there.)
  15201. If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
  15202. is odd and such that the result of |reconstitute| would have been different
  15203. if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
  15204. to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
  15205. A special convention is used in the case |j=0|: Then we assume that the
  15206. translation of |hu[0]| appears in a special list of charnodes starting at
  15207. |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
  15208. a ligature character, involving a left boundary if |init_lft| is |true|.
  15209. This facility is provided for cases when a hyphenated
  15210. word is preceded by punctuation (like single or double quotes) that might
  15211. affect the translation of the beginning of the word.
  15212. @<Glob...@>=
  15213. @!hyphen_passed:small_number; {first hyphen in a ligature, if any}
  15214. @ @<Declare the function called |reconstitute|@>=
  15215. function reconstitute(@!j,@!n:small_number;@!bchar,@!hchar:halfword):
  15216.   small_number;
  15217. label continue,done;
  15218. var @!p:pointer; {temporary register for list manipulation} 
  15219. @!t:pointer; {a node being appended to}
  15220. @!q:four_quarters; {character information or a lig/kern instruction}
  15221. @!cur_rh:halfword; {hyphen character for ligature testing}
  15222. @!test_char:halfword; {hyphen or other character for ligature testing}
  15223. @!w:scaled; {amount of kerning}
  15224. @!k:font_index; {position of current lig/kern instruction}
  15225. begin hyphen_passed:=0; t:=hold_head; w:=0; link(hold_head):=null;
  15226.  {at this point |ligature_present=lft_hit=rt_hit=false|}
  15227. @<Set up data structures with the cursor following position |j|@>;
  15228. continue:@<If there's a ligature or kern at the cursor position, update the data
  15229.   structures, possibly advancing~|j|; continue until the cursor moves@>;
  15230. @<Append a ligature and/or kern to the translation;
  15231.   |goto continue| if the stack of inserted ligatures is nonempty@>;
  15232. reconstitute:=j;
  15233. @ The reconstitution procedure shares many of the global data structures
  15234. by which \TeX\ has processed the words before they were hyphenated.
  15235. There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
  15236. these characters will be tested for possible ligature activity. If
  15237. |ligature_present| then |cur_l| is a ligature character formed from the
  15238. original characters following |cur_q| in the current translation list.
  15239. There is a ``ligature stack'' between the cursor and character |j+1|,
  15240. consisting of pseudo-ligature nodes linked together by their |link| fields.
  15241. This stack is normally empty unless a ligature command has created a new
  15242. character that will need to be processed later. A pseudo-ligature is
  15243. a special node having a |character| field that represents a potential
  15244. ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
  15245. We have
  15246. $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
  15247.   |qi(hu[j+1])|,&if |lig_stack=null| and |j<n|;\cr
  15248.   bchar,&if |lig_stack=null| and |j=n|.\cr}$$
  15249. @<Glob...@>=
  15250. @!cur_l,@!cur_r:halfword; {characters before and after the cursor}
  15251. @!cur_q:pointer; {where a ligature should be detached}
  15252. @!lig_stack:pointer; {unfinished business to the right of the cursor}
  15253. @!ligature_present:boolean; {should a ligature node be made for |cur_l|?}
  15254. @!lft_hit,@!rt_hit:boolean; {did we hit a ligature with a boundary character?}
  15255. @ @d append_charnode_to_t(#)== begin link(t):=get_avail; t:=link(t);
  15256.     font(t):=hf; character(t):=#;
  15257.     end
  15258. @d set_cur_r==begin if j<n then cur_r:=qi(hu[j+1])@+else cur_r:=bchar;
  15259.     if odd(hyf[j]) then cur_rh:=hchar@+else cur_rh:=non_char;
  15260.     end
  15261. @<Set up data structures with the cursor following position |j|@>=
  15262. cur_l:=qi(hu[j]); cur_q:=t;
  15263. if j=0 then
  15264.   begin ligature_present:=init_lig; p:=init_list;
  15265.   if ligature_present then lft_hit:=init_lft;
  15266.   while p>null do
  15267.     begin append_charnode_to_t(character(p)); p:=link(p);
  15268.     end;
  15269.   end
  15270. else if cur_l<non_char then append_charnode_to_t(cur_l);
  15271. lig_stack:=null; set_cur_r
  15272. @ We may want to look at the lig/kern program twice, once for a hyphen
  15273. and once for a normal letter. (The hyphen might appear after the letter
  15274. in the program, so we'd better not try to look for both at once.)
  15275. @<If there's a ligature or kern at the cursor position, update...@>=
  15276. if cur_l=non_char then
  15277.   begin k:=bchar_label[hf];
  15278.   if k=non_address then goto done@+else q:=font_info[k].qqqq;
  15279.   end
  15280. else begin q:=char_info(hf)(cur_l);
  15281.   if char_tag(q)<>lig_tag then goto done;
  15282.   k:=lig_kern_start(hf)(q); q:=font_info[k].qqqq;
  15283.   if skip_byte(q)>stop_flag then
  15284.     begin k:=lig_kern_restart(hf)(q); q:=font_info[k].qqqq;
  15285.     end;
  15286.   end; {now |k| is the starting address of the lig/kern program}
  15287. if cur_rh<non_char then test_char:=cur_rh@+else test_char:=cur_r;
  15288. loop@+begin if next_char(q)=test_char then if skip_byte(q)<=stop_flag then
  15289.     if cur_rh<non_char then
  15290.       begin hyphen_passed:=j; hchar:=non_char; cur_rh:=non_char;
  15291.       goto continue;
  15292.       end
  15293.     else begin if hchar<non_char then if odd(hyf[j]) then
  15294.         begin hyphen_passed:=j; hchar:=non_char;
  15295.         end;
  15296.       if op_byte(q)<kern_flag then
  15297.       @<Carry out a ligature replacement, updating the cursor structure
  15298.         and possibly advancing~|j|; |goto continue| if the cursor doesn't
  15299.         advance, otherwise |goto done|@>;
  15300.       w:=char_kern(hf)(q); goto done; {this kern will be inserted below}
  15301.      end;
  15302.   if skip_byte(q)>=stop_flag then
  15303.     if cur_rh=non_char then goto done
  15304.     else begin cur_rh:=non_char; goto continue;
  15305.       end;
  15306.   k:=k+qo(skip_byte(q))+1; q:=font_info[k].qqqq;
  15307.   end;
  15308. done:
  15309. @ @d wrap_lig(#)==if ligature_present then
  15310.     begin p:=new_ligature(hf,cur_l,link(cur_q));
  15311.     if lft_hit then
  15312.       begin subtype(p):=2; lft_hit:=false;
  15313.       end;
  15314.     if # then if lig_stack=null then
  15315.       begin incr(subtype(p)); rt_hit:=false;
  15316.       end;
  15317.     link(cur_q):=p; t:=p; ligature_present:=false;
  15318.     end
  15319. @d pop_lig_stack==begin if lig_ptr(lig_stack)>null then
  15320.     begin link(t):=lig_ptr(lig_stack); {this is a charnode for |hu[j+1]|}
  15321.     t:=link(t); incr(j);
  15322.     end;
  15323.   p:=lig_stack; lig_stack:=link(p); free_node(p,small_node_size);
  15324.   if lig_stack=null then set_cur_r@+else cur_r:=character(lig_stack);
  15325.   end {if |lig_stack| isn't |null| we have |cur_rh=non_char|}
  15326. @<Append a ligature and/or kern to the translation...@>=
  15327. wrap_lig(rt_hit);
  15328. if w<>0 then
  15329.   begin link(t):=new_kern(w); t:=link(t); w:=0;
  15330.   end;
  15331. if lig_stack>null then
  15332.   begin cur_q:=t; cur_l:=character(lig_stack); ligature_present:=true;
  15333.   pop_lig_stack; goto continue;
  15334.   end
  15335. @ @<Carry out a ligature replacement, updating the cursor structure...@>=
  15336. begin if cur_l=non_char then lft_hit:=true;
  15337. if j=n then if lig_stack=null then rt_hit:=true;
  15338. check_interrupt; {allow a way out in case there's an infinite ligature loop}
  15339. case op_byte(q) of
  15340. qi(1),qi(5):begin cur_l:=rem_byte(q); {\.{=:\?}, \.{=:\?>}}
  15341.   ligature_present:=true;
  15342.   end;
  15343. qi(2),qi(6):begin cur_r:=rem_byte(q); {\.{\?=:}. \.{\?=:>}}
  15344.   if lig_stack>null then character(lig_stack):=cur_r
  15345.   else begin lig_stack:=new_lig_item(cur_r);
  15346.     if j=n then bchar:=non_char
  15347.     else begin p:=get_avail; lig_ptr(lig_stack):=p;
  15348.       character(p):=qi(hu[j+1]); font(p):=hf;
  15349.       end;
  15350.     end;
  15351.   end;
  15352. qi(3):begin cur_r:=rem_byte(q); {\.{\?=:\?}}
  15353.   p:=lig_stack; lig_stack:=new_lig_item(cur_r); link(lig_stack):=p;
  15354.   end;
  15355. qi(7),qi(11):begin wrap_lig(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
  15356.   cur_q:=t; cur_l:=rem_byte(q); ligature_present:=true;
  15357.   end;
  15358. othercases begin cur_l:=rem_byte(q); ligature_present:=true; {\.{=:}}
  15359.   if lig_stack>null then pop_lig_stack
  15360.   else if j=n then goto done
  15361.   else begin append_charnode_to_t(cur_r); incr(j); set_cur_r;
  15362.     end;
  15363.   end
  15364. endcases;
  15365. if op_byte(q)>qi(4) then if op_byte(q)<>qi(7) then goto done;
  15366. goto continue;
  15367. @ Okay, we're ready to insert the potential hyphenations that were found.
  15368. When the following program is executed, we want to append the word
  15369. |hu[1..hn]| after node |ha|, and node |q| should be appended to the result.
  15370. During this process, the variable |i| will be a temporary
  15371. index into |hu|; the variable |j| will be an index to our current position
  15372. in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
  15373. branch; the variable |r| will point to new nodes being created; and
  15374. we need a few new local variables:
  15375. @<Local variables for hyph...@>=
  15376. @!major_tail,@!minor_tail:pointer; {the end of lists in the main and
  15377.   discretionary branches being reconstructed}
  15378. @!c:ASCII_code; {character temporarily replaced by a hyphen}
  15379. @!c_loc:0..63; {where that character came from}
  15380. @!r_count:integer; {replacement count for discretionary}
  15381. @!hyf_node:pointer; {the hyphen, if it exists}
  15382. @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
  15383. @<Reconstitute nodes for the hyphenated word...@>=
  15384. repeat l:=j; j:=reconstitute(j,hn,bchar,qi(hyf_char))+1;
  15385. if hyphen_passed=0 then
  15386.   begin link(s):=link(hold_head);
  15387.   while link(s)>null do s:=link(s);
  15388.   if odd(hyf[j-1]) then
  15389.     begin l:=j; hyphen_passed:=j-1; link(hold_head):=null;
  15390.     end;
  15391.   end;
  15392. if hyphen_passed>0 then
  15393.   @<Create and append a discretionary node as an alternative to the
  15394.     unhyphenated word, and continue to develop both branches until they
  15395.     become equivalent@>;
  15396. until j>hn;
  15397. link(s):=q
  15398. @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
  15399. odd, when both branches of the previous discretionary end at position |j-1|.
  15400. Strictly speaking, we aren't justified in doing this, because we don't know
  15401. that a hyphen after |j-1| is truly independent of those branches. But in almost
  15402. all applications we would rather not lose a potentially valuable hyphenation
  15403. point. (Consider the word `difficult', where the letter `c' is in position |j|.)
  15404. @d advance_major_tail==begin major_tail:=link(major_tail); incr(r_count);
  15405.     end
  15406. @<Create and append a discretionary node as an alternative...@>=
  15407. repeat r:=get_node(small_node_size);
  15408. link(r):=link(hold_head); type(r):=disc_node;
  15409. major_tail:=r; r_count:=0;
  15410. while link(major_tail)>null do advance_major_tail;
  15411. i:=hyphen_passed; hyf[i]:=0;
  15412. @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
  15413. @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|, appending to this
  15414.   list and to |major_tail| until synchronization has been achieved@>;
  15415. @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
  15416.   appropriately@>;
  15417. hyphen_passed:=j-1; link(hold_head):=null;
  15418. until not odd(hyf[j-1])
  15419. @ The new hyphen might combine with the previous character via ligature
  15420. or kern. At this point we have |l-1<=i<j| and |i<hn|.
  15421. @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
  15422. minor_tail:=null; pre_break(r):=null; hyf_node:=new_character(hf,hyf_char);
  15423. if hyf_node<>null then
  15424.   begin incr(i); c:=hu[i]; hu[i]:=hyf_char; free_avail(hyf_node);
  15425.   end;
  15426. while l<=i do
  15427.   begin l:=reconstitute(l,i,font_bchar[hf],non_char)+1;
  15428.   if link(hold_head)>null then
  15429.     begin if minor_tail=null then pre_break(r):=link(hold_head)
  15430.     else link(minor_tail):=link(hold_head);
  15431.     minor_tail:=link(hold_head);
  15432.     while link(minor_tail)>null do minor_tail:=link(minor_tail);
  15433.     end;
  15434.   end;
  15435. if hyf_node<>null then
  15436.   begin hu[i]:=c; {restore the character in the hyphen position}
  15437.   l:=i; decr(i);
  15438.   end
  15439. @ The synchronization algorithm begins with |l=i+1<=j|.
  15440. @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|...@>=
  15441. minor_tail:=null; post_break(r):=null; c_loc:=0;
  15442. if bchar_label[hf]<>non_address then {put left boundary at beginning of new line}
  15443.   begin decr(l); c:=hu[l]; c_loc:=l; hu[l]:=256;
  15444.   end;
  15445. while l<j do
  15446.   begin repeat l:=reconstitute(l,hn,bchar,non_char)+1;
  15447.   if c_loc>0 then
  15448.     begin hu[c_loc]:=c; c_loc:=0;
  15449.     end;
  15450.   if link(hold_head)>null then
  15451.     begin if minor_tail=null then post_break(r):=link(hold_head)
  15452.     else link(minor_tail):=link(hold_head);
  15453.     minor_tail:=link(hold_head);
  15454.     while link(minor_tail)>null do minor_tail:=link(minor_tail);
  15455.     end;
  15456.   until l>=j;
  15457.   while l>j do
  15458.     @<Append characters of |hu[j..@,]| to |major_tail|, advancing~|j|@>;
  15459.   end
  15460. @ @<Append characters of |hu[j..@,]|...@>=
  15461. begin j:=reconstitute(j,hn,bchar,non_char)+1;
  15462. link(major_tail):=link(hold_head);
  15463. while link(major_tail)>null do advance_major_tail;
  15464. @ Ligature insertion can cause a word to grow exponentially in size. Therefore
  15465. we must test the size of |r_count| here, even though the hyphenated text
  15466. was at most 63 characters long.
  15467. @<Move pointer |s| to the end of the current list...@>=
  15468. if r_count>127 then {we have to forget the discretionary hyphen}
  15469.   begin link(s):=link(r); link(r):=null; flush_node_list(r);
  15470.   end
  15471. else begin link(s):=r; replace_count(r):=r_count;
  15472.   end;
  15473. s:=major_tail
  15474. @* \[42] Hyphenation.
  15475. When a word |hc[1..hn]| has been set up to contain a candidate for hyphenation,
  15476. \TeX\ first looks to see if it is in the user's exception dictionary. If not,
  15477. hyphens are inserted based on patterns that appear within the given word,
  15478. using an algorithm due to Frank~M. Liang.
  15479. @^Liang, Franklin Mark@>
  15480. Let's consider Liang's method first, since it is much more interesting than the
  15481. exception-lookup routine.  The algorithm begins by setting |hyf[j]| to zero
  15482. for all |j|, and invalid characters are inserted into |hc[0]|
  15483. and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
  15484. used to see which of a given set of patterns occurs in the word
  15485. |hc[0..(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
  15486. sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
  15487. |hc[(j+1)..(j+k)]|, \TeX\ will set |hyf[j+i]:=@tmax@>(hyf[j+i],@t$n_i$@>)| for
  15488. |0<=i<=k|. After this has been done for each pattern that occurs, a
  15489. discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
  15490. |hyf[j]| is odd, as we have already seen.
  15491. The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
  15492. depends, of course, on the language whose words are being hyphenated, and
  15493. on the degree of hyphenation that is desired. A method for finding
  15494. appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
  15495. hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
  15496. 1983); \TeX\ simply starts with the patterns and works from there.
  15497. @ The patterns are stored in a compact table that is also efficient for
  15498. retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
  15499. Computer Programming \bf3} (1973), 481--505]. We can find each pattern
  15500. $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
  15501. index and then, for |1<=i<=k|,
  15502. setting |@t$z_i$@>:=trie_link@t$(z_{i-1})+p_i$@>|; the pattern will be
  15503. identified by the number $z_k$. Since all the pattern information is
  15504. packed together into a single |trie_link| array, it is necessary to
  15505. prevent confusion between the data from inequivalent patterns, so another
  15506. table is provided such that |trie_char@t$(z_i)=p_i$@>| for all |i|. There
  15507. is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
  15508. associated with $p_1\ldots p_k$.
  15509. Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
  15510. since most of the |n|'s are generally zero. Therefore the number sequences
  15511. are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
  15512. If |trie_op(@t$z_k$@>)<>min_quarterword|, when $p_1\ldots p_k$ has matched
  15513. the letters in |hc[(l-k+1)..l@,]| of language |t|,
  15514. we perform all of the required operations
  15515. for this pattern by carrying out the following little program: Set
  15516. |v:=trie_op(@t$z_k$@>)|. Then set |v:=v+op_start[t]|,
  15517. |hyf[l-hyf_distance[v]]:=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
  15518. and |v:=hyf_next[v]|; repeat, if necessary, until |v=min_quarterword|.
  15519. @<Types...@>=
  15520. @!trie_pointer=0..trie_size; {an index into |trie|}
  15521. @ @d trie_link(#)==trie[#].rh {``downward'' link in a trie}
  15522. @d trie_char(#)==trie[#].b1 {character matched at this trie location}
  15523. @d trie_op(#)==trie[#].b0 {program for hyphenation at this trie location}
  15524. @<Glob...@>=
  15525. @!trie:array[trie_pointer] of two_halves; {|trie_link|, |trie_char|, |trie_op|}
  15526. @!hyf_distance:array[1..trie_op_size] of small_number; {position |k-j| of $n_j$}
  15527. @!hyf_num:array[1..trie_op_size] of small_number; {value of $n_j$}
  15528. @!hyf_next:array[1..trie_op_size] of quarterword; {continuation code}
  15529. @!op_start:array[ASCII_code] of 0..trie_op_size; {offset for current language}
  15530. @ @<Local variables for hyph...@>=
  15531. @!z:trie_pointer; {an index into |trie|}
  15532. @!v:integer; {an index into |hyf_distance|, etc.}
  15533. @ Assuming that these auxiliary tables have been set up properly, the
  15534. hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
  15535. to the impossible value 256, in order to guarantee that |hc[hn+3]| will
  15536. never be fetched.
  15537. @<Find hyphen locations for the word in |hc|...@>=
  15538. for j:=0 to hn do hyf[j]:=0;
  15539. @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
  15540.   |hyf| containing the hyphens) if an entry is found@>;
  15541. if trie_char(cur_lang+1)<>qi(cur_lang) then return; {no patterns for |cur_lang|}
  15542. hc[0]:=0; hc[hn+1]:=0; hc[hn+2]:=256; {insert delimiters}
  15543. for j:=0 to hn-r_hyf+1 do
  15544.   begin z:=trie_link(cur_lang+1)+hc[j]; l:=j;
  15545.   while hc[l]=qo(trie_char(z)) do
  15546.     begin if trie_op(z)<>min_quarterword then
  15547.       @<Store \(m)maximum values in the |hyf| table@>;
  15548.     incr(l); z:=trie_link(z)+hc[l];
  15549.     end;
  15550.   end;
  15551. found: for j:=0 to l_hyf-1 do hyf[j]:=0;
  15552. for j:=0 to r_hyf-1 do hyf[hn-j]:=0
  15553. @ @<Store \(m)maximum values in the |hyf| table@>=
  15554. begin v:=trie_op(z);
  15555. repeat v:=v+op_start[cur_lang]; i:=l-hyf_distance[v];
  15556. if hyf_num[v]>hyf[i] then hyf[i]:=hyf_num[v];
  15557. v:=hyf_next[v];
  15558. until v=min_quarterword;
  15559. @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
  15560. organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
  15561. @^Amble, Ole@> @^Knuth, Donald Ervin@>
  15562. Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
  15563. $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
  15564. \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
  15565. $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
  15566. \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
  15567. is to arrange the table so that a given word $\alpha$ can be sought by computing
  15568. a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
  15569. \dots, until encountering the first word $\L\alpha$. If this word is
  15570. different from $\alpha$, we can conclude that $\alpha$ is not in the table.
  15571. The words in the table point to lists in |mem| that specify hyphen positions
  15572. in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
  15573. the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
  15574. $c_{k+1}$.
  15575. @<Types...@>=
  15576. @!hyph_pointer=0..hyph_size; {an index into the ordered hash table}
  15577. @ @<Glob...@>=
  15578. @!hyph_word:array[hyph_pointer] of str_number; {exception words}
  15579. @!hyph_list:array[hyph_pointer] of pointer; {list of hyphen positions}
  15580. @!hyph_count:hyph_pointer; {the number of words in the exception dictionary}
  15581. @ @<Local variables for init...@>=
  15582. @!z:hyph_pointer; {runs through the exception dictionary}
  15583. @ @<Set init...@>=
  15584. for z:=0 to hyph_size do
  15585.   begin hyph_word[z]:=0; hyph_list[z]:=null;
  15586.   end;
  15587. hyph_count:=0;
  15588. @ The algorithm for exception lookup is quite simple, as soon as we have
  15589. a few more local variables to work with.
  15590. @<Local variables for hyph...@>=
  15591. @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
  15592. @!k:str_number; {an index into |str_start|}
  15593. @!u:pool_pointer; {an index into |str_pool|}
  15594. @ First we compute the hash code |h|, then we search until we either
  15595. find the word or we don't. Words from different languages are kept
  15596. separate by appending the language code to the string.
  15597. @<Look for the word |hc[1...@>=
  15598. h:=hc[1]; incr(hn); hc[hn]:=cur_lang;
  15599. for j:=2 to hn do h:=(h+h+hc[j]) mod hyph_size;
  15600. loop@+  begin @<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|,
  15601.     |goto not_found|; but if the two strings are equal,
  15602.     set |hyf| to the hyphen positions and |goto found|@>;
  15603.   if h>0 then decr(h)@+else h:=hyph_size;
  15604.   end;
  15605. not_found: decr(hn)
  15606. @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
  15607. k:=hyph_word[h]; if k=0 then goto not_found;
  15608. if length(k)<hn then goto not_found;
  15609. if length(k)=hn then
  15610.   begin j:=1; u:=str_start[k];
  15611.   repeat if so(str_pool[u])<hc[j] then goto not_found;
  15612.   if so(str_pool[u])>hc[j] then goto done;
  15613.   incr(j); incr(u);
  15614.   until j>hn;
  15615.   @<Insert hyphens as specified in |hyph_list[h]|@>;
  15616.   decr(hn); goto found;
  15617.   end;
  15618. done:
  15619. @ @<Insert hyphens as specified...@>=
  15620. s:=hyph_list[h];
  15621. while s<>null do
  15622.   begin hyf[info(s)]:=1; s:=link(s);
  15623.   end
  15624. @ @<Search |hyph_list| for pointers to |p|@>=
  15625. for q:=0 to hyph_size do
  15626.   begin if hyph_list[q]=p then
  15627.     begin print_nl("HYPH("); print_int(q); print_char(")");
  15628.     end;
  15629.   end
  15630. @ We have now completed the hyphenation routine, so the |line_break| procedure
  15631. is finished at last. Since the hyphenation exception table is fresh in our
  15632. minds, it's a good time to deal with the routine that adds new entries to it.
  15633. When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
  15634. |new_hyph_exceptions| to do the right thing.
  15635. @d set_cur_lang==if language<=0 then cur_lang:=0
  15636.   else if language>255 then cur_lang:=0
  15637.   else cur_lang:=language
  15638. @p procedure new_hyph_exceptions; {enters new exceptions}
  15639. label reswitch, exit, found, not_found;
  15640. var n:0..64; {length of current word; not always a |small_number|}
  15641. @!j:0..64; {an index into |hc|}
  15642. @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
  15643. @!k:str_number; {an index into |str_start|}
  15644. @!p:pointer; {head of a list of hyphen positions}
  15645. @!q:pointer; {used when creating a new node for list |p|}
  15646. @!s,@!t:str_number; {strings being compared or stored}
  15647. @!u,@!v:pool_pointer; {indices into |str_pool|}
  15648. begin scan_left_brace; {a left brace must follow \.{\\hyphenation}}
  15649. set_cur_lang;
  15650. @<Enter as many hyphenation exceptions as are listed,
  15651. until coming to a right brace; then |return|@>;
  15652. exit:end;
  15653. @ @<Enter as many...@>=
  15654. n:=0; p:=null;
  15655. loop@+  begin get_x_token;
  15656.   reswitch: case cur_cmd of
  15657.   letter,other_char,char_given:@<Append a new letter or hyphen@>;
  15658.   char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
  15659.     goto reswitch;
  15660.     end;
  15661.   spacer,right_brace: begin if n>1 then @<Enter a hyphenation exception@>;
  15662.     if cur_cmd=right_brace then return;
  15663.     n:=0; p:=null;
  15664.     end;
  15665.   othercases @<Give improper \.{\\hyphenation} error@>
  15666.   endcases;
  15667.   end
  15668. @ @<Give improper \.{\\hyph...@>=
  15669. begin print_err("Improper "); print_esc("hyphenation");
  15670. @.Improper \\hyphenation...@>
  15671.   print(" will be flushed");
  15672. help2("Hyphenation exceptions must contain only letters")@/
  15673.   ("and hyphens. But continue; I'll forgive and forget.");
  15674. error;
  15675. @ @<Append a new letter or hyphen@>=
  15676. if cur_chr="-" then @<Append the value |n| to list |p|@>
  15677. else  begin if lc_code(cur_chr)=0 then
  15678.     begin print_err("Not a letter");
  15679. @.Not a letter@>
  15680.     help2("Letters in \hyphenation words must have \lccode>0.")@/
  15681.       ("Proceed; I'll ignore the character I just read.");
  15682.     error;
  15683.     end
  15684.   else if n<63 then
  15685.     begin incr(n); hc[n]:=lc_code(cur_chr);
  15686.     end;
  15687.   end
  15688. @ @<Append the value |n| to list |p|@>=
  15689. begin if n<63 then
  15690.   begin q:=get_avail; link(q):=p; info(q):=n; p:=q;
  15691.   end;
  15692. @ @<Enter a hyphenation exception@>=
  15693. begin incr(n); hc[n]:=cur_lang; str_room(n); h:=0;
  15694. for j:=1 to n do
  15695.   begin h:=(h+h+hc[j]) mod hyph_size;
  15696.   append_char(hc[j]);
  15697.   end;
  15698. s:=make_string;
  15699. @<Insert the \(p)pair |(s,p)| into the exception table@>;
  15700. @ @<Insert the \(p)pair |(s,p)|...@>=
  15701. if hyph_count=hyph_size then overflow("exception dictionary",hyph_size);
  15702. @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
  15703. incr(hyph_count);
  15704. while hyph_word[h]<>0 do
  15705.   begin @<If the string |hyph_word[h]| is less than \(or)or equal to
  15706.   |s|, interchange |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
  15707.   if h>0 then decr(h)@+else h:=hyph_size;
  15708.   end;
  15709. hyph_word[h]:=s; hyph_list[h]:=p
  15710. @ @<If the string |hyph_word[h]| is less than \(or)...@>=
  15711. k:=hyph_word[h];
  15712. if length(k)<length(s) then goto found;
  15713. if length(k)>length(s) then goto not_found;
  15714. u:=str_start[k]; v:=str_start[s];
  15715. repeat if str_pool[u]<str_pool[v] then goto found;
  15716. if str_pool[u]>str_pool[v] then goto not_found;
  15717. incr(u); incr(v);
  15718. until u=str_start[k+1];
  15719. found:q:=hyph_list[h]; hyph_list[h]:=p; p:=q;@/
  15720. t:=hyph_word[h]; hyph_word[h]:=s; s:=t;
  15721. not_found:
  15722. @* \[43] Initializing the hyphenation tables.
  15723. The trie for \TeX's hyphenation algorithm is built from a sequence of
  15724. patterns following a \.{\\patterns} specification. Such a specification
  15725. is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
  15726. and for the initialization program itself would only clutter up the
  15727. production version of \TeX\ with a lot of deadwood.
  15728. The first step is to build a trie that is linked, instead of packed
  15729. into sequential storage, so that insertions are readily made.
  15730. After all patterns have been processed, \.{INITEX}
  15731. compresses the linked trie by identifying common subtries. Finally the
  15732. trie is packed into the efficient sequential form that the hyphenation
  15733. algorithm actually uses.
  15734. @<Declare subprocedures for |line_break|@>=
  15735. @!init @<Declare procedures for preprocessing hyphenation patterns@>@;
  15736. @ Before we discuss trie building in detail, let's consider the simpler
  15737. problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
  15738. Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
  15739. a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
  15740. notation above. We want the corresponding |trie_op| code |v| to have
  15741. |hyf_distance[v]=3|, |hyf_num[v]=2|, and |hyf_next[v]=@t$v^\prime$@>|,
  15742. where the auxiliary |trie_op| code $v^\prime$ has
  15743. |hyf_distance[@t$v^\prime$@>]=0|, |hyf_num[@t$v^\prime$@>]=1|, and
  15744. |hyf_next[@t$v^\prime$@>]=min_quarterword|.
  15745. \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
  15746. below, by setting
  15747. $$\hbox{|@t$v^\prime$@>:=new_trie_op(0,1,min_quarterword)|,\qquad
  15748. |v:=new_trie_op(3,2,@t$v^\prime$@>)|.}$$
  15749. This subroutine looks up its three
  15750. parameters in a special hash table, assigning a new value only if these
  15751. three have not appeared before for the current language.
  15752. The hash table is called |trie_op_hash|, and the number of entries it contains
  15753. is |trie_op_ptr|.
  15754. @<Glob...@>=
  15755. @!init@! trie_op_hash:array[-trie_op_size..trie_op_size] of 0..trie_op_size;
  15756.   {trie op codes for quadruples}
  15757. @!trie_used:array[ASCII_code] of quarterword;
  15758.   {largest opcode used so far for this language}
  15759. @!trie_op_lang:array[1..trie_op_size] of ASCII_code;
  15760.   {language part of a hashed quadruple}
  15761. @!trie_op_val:array[1..trie_op_size] of quarterword;
  15762.   {opcode corresponding to a hashed quadruple}
  15763. @!trie_op_ptr:0..trie_op_size; {number of stored ops so far}
  15764. @ It's tempting to remove the |overflow| stops in the following procedure;
  15765. |new_trie_op| could return |min_quarterword| (thereby simply ignoring
  15766. part of a hyphenation pattern) instead of aborting the job. However, that would
  15767. lead to different hyphenation results on different installations of \TeX\
  15768. using the same patterns. The |overflow| stops are necessary for portability
  15769. of patterns.
  15770. @<Declare procedures for preprocessing hyph...@>=
  15771. function new_trie_op(@!d,@!n:small_number;@!v:quarterword):quarterword;
  15772. label exit;
  15773. var h:-trie_op_size..trie_op_size; {trial hash location}
  15774. @!u:quarterword; {trial op code}
  15775. @!l:0..trie_op_size; {pointer to stored data}
  15776. begin h:=abs(n+313*d+361*v+1009*cur_lang) mod (trie_op_size+trie_op_size)
  15777.   - trie_op_size;
  15778. loop@+  begin l:=trie_op_hash[h];
  15779.   if l=0 then {empty position found for a new op}
  15780.     begin if trie_op_ptr=trie_op_size then
  15781.       overflow("pattern memory ops",trie_op_size);
  15782.     u:=trie_used[cur_lang];
  15783.     if u=max_quarterword then
  15784.       overflow("pattern memory ops per language",
  15785.         max_quarterword-min_quarterword);
  15786.     incr(trie_op_ptr); incr(u); trie_used[cur_lang]:=u;
  15787.     hyf_distance[trie_op_ptr]:=d;
  15788.     hyf_num[trie_op_ptr]:=n; hyf_next[trie_op_ptr]:=v;
  15789.     trie_op_lang[trie_op_ptr]:=cur_lang; trie_op_hash[h]:=trie_op_ptr;
  15790.     trie_op_val[trie_op_ptr]:=u; new_trie_op:=u; return;
  15791.     end;
  15792.   if (hyf_distance[l]=d)and(hyf_num[l]=n)and(hyf_next[l]=v)
  15793.    and(trie_op_lang[l]=cur_lang) then
  15794.     begin new_trie_op:=trie_op_val[l]; return;
  15795.     end;
  15796.   if h>-trie_op_size then decr(h)@+else h:=trie_op_size;
  15797.   end;
  15798. exit:end;
  15799. @ After |new_trie_op| has compressed the necessary opcode information,
  15800. plenty of information is available to unscramble the data into the
  15801. final form needed by our hyphenation algorithm.
  15802. @<Sort \(t)the hyphenation op tables into proper order@>=
  15803. op_start[0]:=-min_quarterword;
  15804. for j:=1 to 255 do op_start[j]:=op_start[j-1]+qo(trie_used[j-1]);
  15805. for j:=1 to trie_op_ptr do
  15806.   trie_op_hash[j]:=op_start[trie_op_lang[j]]+trie_op_val[j]; {destination}
  15807. for j:=1 to trie_op_ptr do while trie_op_hash[j]>j do
  15808.   begin k:=trie_op_hash[j];@/
  15809.   t:=hyf_distance[k]; hyf_distance[k]:=hyf_distance[j]; hyf_distance[j]:=t;@/
  15810.   t:=hyf_num[k]; hyf_num[k]:=hyf_num[j]; hyf_num[j]:=t;@/
  15811.   t:=hyf_next[k]; hyf_next[k]:=hyf_next[j]; hyf_next[j]:=t;@/
  15812.   trie_op_hash[j]:=trie_op_hash[k]; trie_op_hash[k]:=k;
  15813.   end
  15814. @ Before we forget how to initialize the data structures that have been
  15815. mentioned so far, let's write down the code that gets them started.
  15816. @<Initialize table entries...@>=
  15817. for k:=-trie_op_size to trie_op_size do trie_op_hash[k]:=0;
  15818. for k:=0 to 255 do trie_used[k]:=min_quarterword;
  15819. trie_op_ptr:=0;
  15820. @ The linked trie that is used to preprocess hyphenation patterns appears
  15821. in several global arrays. Each node represents an instruction of the form
  15822. ``if you see character |c|, then perform operation |o|, move to the
  15823. next character, and go to node |l|; otherwise go to node |r|.''
  15824. The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
  15825. |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
  15826. is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
  15827. pointers are represented by zero. To initialize the trie, we simply
  15828. set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
  15829. arbitrary value, since the algorithm may access it.
  15830. The algorithms maintain the condition
  15831. $$\hbox{|trie_c[trie_r[z]]>trie_c[z]|\qquad
  15832. whenever |z<>0| and |trie_r[z]<>0|};$$ in other words, sibling nodes are
  15833. ordered by their |c| fields.
  15834. @d trie_root==trie_l[0] {root of the linked trie}
  15835. @<Glob...@>=
  15836. @!init @!trie_c:packed array[trie_pointer] of packed_ASCII_code;
  15837.   {characters to match}
  15838. @t\hskip10pt@>@!trie_o:packed array[trie_pointer] of quarterword;
  15839.   {operations to perform}
  15840. @t\hskip10pt@>@!trie_l:packed array[trie_pointer] of trie_pointer;
  15841.   {left subtrie links}
  15842. @t\hskip10pt@>@!trie_r:packed array[trie_pointer] of trie_pointer;
  15843.   {right subtrie links}
  15844. @t\hskip10pt@>@!trie_ptr:trie_pointer; {the number of nodes in the trie}
  15845. @t\hskip10pt@>@!trie_hash:packed array[trie_pointer] of trie_pointer;
  15846.   {used to identify equivalent subtries}
  15847. @ Let us suppose that a linked trie has already been constructed.
  15848. Experience shows that we can often reduce its size by recognizing common
  15849. subtries; therefore another hash table is introduced for this purpose,
  15850. somewhat similar to |trie_op_hash|. The new hash table will be
  15851. initialized to zero.
  15852. The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
  15853. that it has seen, otherwise it returns the number of the first equivalent
  15854. node that it has seen.
  15855. Notice that we might make subtries equivalent even if they correspond to
  15856. patterns for different languages, in which the trie ops might mean quite
  15857. different things. That's perfectly all right.
  15858. @<Declare procedures for preprocessing hyph...@>=
  15859. function trie_node(@!p:trie_pointer):trie_pointer; {converts
  15860.   to a canonical form}
  15861. label exit;
  15862. var h:trie_pointer; {trial hash location}
  15863. @!q:trie_pointer; {trial trie node}
  15864. begin h:=abs(trie_c[p]+1009*trie_o[p]+@|
  15865.     2718*trie_l[p]+3142*trie_r[p]) mod trie_size;
  15866. loop@+  begin q:=trie_hash[h];
  15867.   if q=0 then
  15868.     begin trie_hash[h]:=p; trie_node:=p; return;
  15869.     end;
  15870.   if (trie_c[q]=trie_c[p])and(trie_o[q]=trie_o[p])and@|
  15871.     (trie_l[q]=trie_l[p])and(trie_r[q]=trie_r[p]) then
  15872.     begin trie_node:=q; return;
  15873.     end;
  15874.   if h>0 then decr(h)@+else h:=trie_size;
  15875.   end;
  15876. exit:end;
  15877. @ A neat recursive procedure is now able to compress a trie by
  15878. traversing it and applying |trie_node| to its nodes in ``bottom up''
  15879. fashion. We will compress the entire trie by clearing |trie_hash| to
  15880. zero and then saying `|trie_root:=compress_trie(trie_root)|'.
  15881. @^recursion@>
  15882. @<Declare procedures for preprocessing hyph...@>=
  15883. function compress_trie(@!p:trie_pointer):trie_pointer;
  15884. begin if p=0 then compress_trie:=0
  15885. else  begin trie_l[p]:=compress_trie(trie_l[p]);
  15886.   trie_r[p]:=compress_trie(trie_r[p]);
  15887.   compress_trie:=trie_node(p);
  15888.   end;
  15889. @ The compressed trie will be packed into the |trie| array using a
  15890. ``top-down first-fit'' procedure. This is a little tricky, so the reader
  15891. should pay close attention: The |trie_hash| array is cleared to zero
  15892. again and renamed |trie_ref| for this phase of the operation; later on,
  15893. |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
  15894. smallest character
  15895. in a family and if the characters |c| of that family have been allocated to
  15896. locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
  15897. are in use will have |trie_link=0|, while the unused holes in |trie|
  15898. will be doubly linked with |trie_link| pointing to the next larger vacant
  15899. location and |trie_back| pointing to the next smaller one. This double
  15900. linking will have been carried out only as far as |trie_max|, where
  15901. |trie_max| is the largest index of |trie| that will be needed.
  15902. To save time at the low end of the trie, we maintain array entries
  15903. |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
  15904. Another array |trie_taken| tells whether or not a given location is
  15905. equal to |trie_ref[p]| for some |p|; this array is used to ensure that
  15906. distinct nodes in the compressed trie will have distinct |trie_ref|
  15907. entries.
  15908. @d trie_ref==trie_hash {where linked trie families go into |trie|}
  15909. @d trie_back(#)==trie[#].lh {backward links in |trie| holes}
  15910. @<Glob...@>=
  15911. @!init@!trie_taken:packed array[1..trie_size] of boolean;
  15912.   {does a family start here?}
  15913. @t\hskip10pt@>@!trie_min:array[ASCII_code] of trie_pointer;
  15914.   {the first possible slot for each character}
  15915. @t\hskip10pt@>@!trie_max:trie_pointer; {largest location used in |trie|}
  15916. @t\hskip10pt@>@!trie_not_ready:boolean; {is the trie still in linked form?}
  15917. @ Each time \.{\\patterns} appears, it contributes further patterns to
  15918. the future trie, which will be built only when hyphenation is attempted or
  15919. when a format file is dumped. The boolean variable |trie_not_ready|
  15920. will change to |false| when the trie is compressed; this will disable
  15921. further patterns.
  15922. @<Initialize table entries...@>=
  15923. trie_not_ready:=true; trie_root:=0; trie_c[0]:=si(0); trie_ptr:=0;
  15924. @ Here is how the trie-compression data structures are initialized.
  15925. If storage is tight, it would be possible to overlap |trie_op_hash|,
  15926. |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
  15927. because we finish with the former just before we need the latter.
  15928. @<Get ready to compress the trie@>=
  15929. @<Sort \(t)the hyphenation...@>;
  15930. for p:=0 to trie_size do trie_hash[p]:=0;
  15931. trie_root:=compress_trie(trie_root); {identify equivalent subtries}
  15932. for p:=0 to trie_ptr do trie_ref[p]:=0;
  15933. for p:=0 to 255 do trie_min[p]:=p+1;
  15934. trie_link(0):=1; trie_max:=0
  15935. @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
  15936. a trie family starting at a given node |p| will fit into vacant positions
  15937. starting at |z|. If |c=trie_c[p]|, this means that location |z-c| must
  15938. not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
  15939. must be vacant for all characters $c^\prime$ in the family. The procedure
  15940. sets |trie_ref[p]| to |z-c| when the first fit has been found.
  15941. @<Declare procedures for preprocessing hyph...@>=
  15942. procedure first_fit(@!p:trie_pointer); {packs a family into |trie|}
  15943. label not_found,found;
  15944. var h:trie_pointer; {candidate for |trie_ref[p]|}
  15945. @!z:trie_pointer; {runs through holes}
  15946. @!q:trie_pointer; {runs through the family starting at |p|}
  15947. @!c:ASCII_code; {smallest character in the family}
  15948. @!l,@!r:trie_pointer; {left and right neighbors}
  15949. @!ll:1..256; {upper limit of |trie_min| updating}
  15950. begin c:=so(trie_c[p]);
  15951. z:=trie_min[c]; {get the first conceivably good hole}
  15952. loop@+  begin h:=z-c;@/
  15953.   @<Ensure that |trie_max>=h+256|@>;
  15954.   if trie_taken[h] then goto not_found;
  15955.   @<If all characters of the family fit relative to |h|, then
  15956.     |goto found|,\30\ otherwise |goto not_found|@>;
  15957.   not_found: z:=trie_link(z); {move to the next hole}
  15958.   end;
  15959. found: @<Pack the family into |trie| relative to |h|@>;
  15960. @ By making sure that |trie_max| is at least |h+256|, we can be sure that
  15961. |trie_max>z|, since |h=z-c|. It follows that location |trie_max| will
  15962. never be occupied in |trie|, and we will have |trie_max>=trie_link(z)|.
  15963. @<Ensure that |trie_max>=h+256|@>=
  15964. if trie_max<h+256 then
  15965.   begin if trie_size<=h+256 then overflow("pattern memory",trie_size);
  15966. @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
  15967.   repeat incr(trie_max); trie_taken[trie_max]:=false;
  15968.   trie_link(trie_max):=trie_max+1; trie_back(trie_max):=trie_max-1;
  15969.   until trie_max=h+256;
  15970.   end
  15971. @ @<If all characters of the family fit relative to |h|...@>=
  15972. q:=trie_r[p];
  15973. while q>0 do
  15974.   begin if trie_link(h+so(trie_c[q]))=0 then goto not_found;
  15975.   q:=trie_r[q];
  15976.   end;
  15977. goto found
  15978. @ @<Pack the family into |trie| relative to |h|@>=
  15979. trie_taken[h]:=true; trie_ref[p]:=h; q:=p;
  15980. repeat z:=h+so(trie_c[q]); l:=trie_back(z); r:=trie_link(z);
  15981. trie_back(r):=l; trie_link(l):=r; trie_link(z):=0;
  15982. if l<256 then
  15983.   begin if z<256 then ll:=z @+else ll:=256;
  15984.   repeat trie_min[l]:=r; incr(l);
  15985.   until l=ll;
  15986.   end;
  15987. q:=trie_r[q];
  15988. until q=0
  15989. @ To pack the entire linked trie, we use the following recursive procedure.
  15990. @^recursion@>
  15991. @<Declare procedures for preprocessing hyph...@>=
  15992. procedure trie_pack(@!p:trie_pointer); {pack subtries of a family}
  15993. var q:trie_pointer; {a local variable that need not be saved on recursive calls}
  15994. begin repeat q:=trie_l[p];
  15995. if (q>0)and(trie_ref[q]=0) then
  15996.   begin first_fit(q); trie_pack(q);
  15997.   end;
  15998. p:=trie_r[p];
  15999. until p=0;
  16000. @ When the whole trie has been allocated into the sequential table, we
  16001. must go through it once again so that |trie| contains the correct
  16002. information. Null pointers in the linked trie will be represented by the
  16003. value~0, which properly implements an ``empty'' family.
  16004. @<Move the data into |trie|@>=
  16005. h.rh:=0; h.b0:=min_quarterword; h.b1:=min_quarterword; {|trie_link:=0|,
  16006.   |trie_op:=min_quarterword|, |trie_char:=qi(0)|}
  16007. if trie_root=0 then {no patterns were given}
  16008.   begin for r:=0 to 256 do trie[r]:=h;
  16009.   trie_max:=256;
  16010.   end
  16011. else begin trie_fix(trie_root); {this fixes the non-holes in |trie|}
  16012.   r:=0; {now we will zero out all the holes}
  16013.   repeat s:=trie_link(r); trie[r]:=h; r:=s;
  16014.   until r>trie_max;
  16015.   end;
  16016. trie_char(0):=qi("?"); {make |trie_char(c)<>c| for all |c|}
  16017. @ The fixing-up procedure is, of course, recursive. Since the linked trie
  16018. usually has overlapping subtries, the same data may be moved several
  16019. times; but that causes no harm, and at most as much work is done as it
  16020. took to build the uncompressed trie.
  16021. @^recursion@>
  16022. @<Declare procedures for preprocessing hyph...@>=
  16023. procedure trie_fix(@!p:trie_pointer); {moves |p| and its siblings into |trie|}
  16024. var q:trie_pointer; {a local variable that need not be saved on recursive calls}
  16025. @!c:ASCII_code; {another one that need not be saved}
  16026. @!z:trie_pointer; {|trie| reference; this local variable must be saved}
  16027. begin z:=trie_ref[p];
  16028. repeat q:=trie_l[p]; c:=so(trie_c[p]);
  16029. trie_link(z+c):=trie_ref[q]; trie_char(z+c):=qi(c); trie_op(z+c):=trie_o[p];
  16030. if q>0 then trie_fix(q);
  16031. p:=trie_r[p];
  16032. until p=0;
  16033. @ Now let's go back to the easier problem, of building the linked
  16034. trie.  When \.{INITEX} has scanned the `\.{\\patterns}' control
  16035. sequence, it calls on |new_patterns| to do the right thing.
  16036. @<Declare procedures for preprocessing hyph...@>=
  16037. procedure new_patterns; {initializes the hyphenation pattern data}
  16038. label done, done1;
  16039. var k,@!l:0..64; {indices into |hc| and |hyf|;
  16040.                   not always in |small_number| range}
  16041. @!digit_sensed:boolean; {should the next digit be treated as a letter?}
  16042. @!v:quarterword; {trie op code}
  16043. @!p,@!q:trie_pointer; {nodes of trie traversed during insertion}
  16044. @!first_child:boolean; {is |p=trie_l[q]|?}
  16045. @!c:ASCII_code; {character being inserted}
  16046. begin if trie_not_ready then
  16047.   begin set_cur_lang; scan_left_brace; {a left brace must follow \.{\\patterns}}
  16048.   @<Enter all of the patterns into a linked trie, until coming to a right
  16049.   brace@>;
  16050.   end
  16051. else begin print_err("Too late for "); print_esc("patterns");
  16052.   help1("All patterns must be given before typesetting begins.");
  16053.   error; link(garbage):=scan_toks(false,false); flush_list(def_ref);
  16054.   end;
  16055. @ Novices are not supposed to be using \.{\\patterns}, so the error
  16056. messages are terse. (Note that all error messages appear in \TeX's string
  16057. pool, even if they are used only by \.{INITEX}.)
  16058. @<Enter all of the patterns into a linked trie...@>=
  16059. k:=0; hyf[0]:=0; digit_sensed:=false;
  16060. loop@+  begin get_x_token;
  16061.   case cur_cmd of
  16062.   letter,other_char:@<Append a new letter or a hyphen level@>;
  16063.   spacer,right_brace: begin if k>0 then
  16064.       @<Insert a new pattern into the linked trie@>;
  16065.     if cur_cmd=right_brace then goto done;
  16066.     k:=0; hyf[0]:=0; digit_sensed:=false;
  16067.     end;
  16068.   othercases begin print_err("Bad "); print_esc("patterns");
  16069. @.Bad \\patterns@>
  16070.     help1("(See Appendix H.)"); error;
  16071.     end
  16072.   endcases;
  16073.   end;
  16074. done:
  16075. @ @<Append a new letter or a hyphen level@>=
  16076. if digit_sensed or(cur_chr<"0")or(cur_chr>"9") then
  16077.   begin if cur_chr="." then cur_chr:=0 {edge-of-word delimiter}
  16078.   else  begin cur_chr:=lc_code(cur_chr);
  16079.     if cur_chr=0 then
  16080.       begin print_err("Nonletter");
  16081. @.Nonletter@>
  16082.       help1("(See Appendix H.)"); error;
  16083.       end;
  16084.     end;
  16085.   if k<63 then
  16086.     begin incr(k); hc[k]:=cur_chr; hyf[k]:=0; digit_sensed:=false;
  16087.     end;
  16088.   end
  16089. else if k<63 then
  16090.   begin hyf[k]:=cur_chr-"0"; digit_sensed:=true;
  16091.   end
  16092. @ When the following code comes into play, the pattern $p_1\ldots p_k$
  16093. appears in |hc[1..k]|, and the corresponding sequence of numbers $n_0\ldots
  16094. n_k$ appears in |hyf[0..k]|.
  16095. @<Insert a new pattern into the linked trie@>=
  16096. begin @<Compute the trie op code, |v|, and set |l:=0|@>;
  16097. q:=0; hc[0]:=cur_lang;
  16098. while l<=k do
  16099.   begin c:=hc[l]; incr(l); p:=trie_l[q]; first_child:=true;
  16100.   while (p>0)and(c>so(trie_c[p])) do
  16101.     begin q:=p; p:=trie_r[q]; first_child:=false;
  16102.     end;
  16103.   if (p=0)or(c<so(trie_c[p])) then
  16104.     @<Insert a new trie node between |q| and |p|, and
  16105.       make |p| point to it@>;
  16106.   q:=p; {now node |q| represents $p_1\ldots p_l$}
  16107.   end;
  16108. if trie_o[q]<>min_quarterword then
  16109.   begin print_err("Duplicate pattern");
  16110. @.Duplicate pattern@>
  16111.   help1("(See Appendix H.)"); error;
  16112.   end;
  16113. trie_o[q]:=v;
  16114. @ @<Insert a new trie node between |q| and |p|...@>=
  16115. begin if trie_ptr=trie_size then overflow("pattern memory",trie_size);
  16116. @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
  16117. incr(trie_ptr); trie_r[trie_ptr]:=p; p:=trie_ptr; trie_l[p]:=0;
  16118. if first_child then trie_l[q]:=p@+else trie_r[q]:=p;
  16119. trie_c[p]:=si(c); trie_o[p]:=min_quarterword;
  16120. @ @<Compute the trie op code, |v|...@>=
  16121. if hc[1]=0 then hyf[0]:=0;
  16122. if hc[k]=0 then hyf[k]:=0;
  16123. l:=k; v:=min_quarterword;
  16124. loop@+  begin if hyf[l]<>0 then v:=new_trie_op(k-l,hyf[l],v);
  16125.   if l>0 then decr(l)@+else goto done1;
  16126.   end;
  16127. done1:
  16128. @ Finally we put everything together: Here is how the trie gets to its
  16129. final, efficient form.
  16130. The following packing routine is rigged so that the root of the linked
  16131. tree gets mapped into location 1 of |trie|, as required by the hyphenation
  16132. algorithm. This happens because the first call of |first_fit| will
  16133. ``take'' location~1.
  16134. @<Declare procedures for preprocessing hyphenation patterns@>=
  16135. procedure init_trie;
  16136. var @!p:trie_pointer; {pointer for initialization}
  16137. @!j,@!k,@!t:integer; {all-purpose registers for initialization}
  16138. @!r,@!s:trie_pointer; {used to clean up the packed |trie|}
  16139. @!h:two_halves; {template used to zero out |trie|'s holes}
  16140. begin @<Get ready to compress the trie@>;
  16141. if trie_root<>0 then
  16142.   begin first_fit(trie_root); trie_pack(trie_root);
  16143.   end;
  16144. @<Move the data into |trie|@>;
  16145. trie_not_ready:=false;
  16146. @* \[44] Breaking vertical lists into pages.
  16147. The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
  16148. is considerably simpler than |line_break| because it doesn't have to
  16149. worry about hyphenation, and because its mission is to discover a single
  16150. break instead of an optimum sequence of breakpoints.  But before we get
  16151. into the details of |vsplit|, we need to consider a few more basic things.
  16152. @ A subroutine called |prune_page_top| takes a pointer to a vlist and
  16153. returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
  16154. have been deleted before the first box or rule node. However, the first
  16155. box or rule is actually preceded by a newly created glue node designed so that
  16156. the topmost baseline will be at distance |split_top_skip| from the top,
  16157. whenever this is possible without backspacing.
  16158. In this routine and those that follow, we make use of the fact that a
  16159. vertical list contains no character nodes, hence the |type| field exists
  16160. for each node in the list.
  16161. @^data structure assumptions@>
  16162. @p function prune_page_top(@!p:pointer):pointer; {adjust top after page break}
  16163. var prev_p:pointer; {lags one step behind |p|}
  16164. @!q:pointer; {temporary variable for list manipulation}
  16165. begin prev_p:=temp_head; link(temp_head):=p;
  16166. while p<>null do
  16167.   case type(p) of
  16168.   hlist_node,vlist_node,rule_node:@<Insert glue for |split_top_skip|
  16169.     and set~|p:=null|@>;
  16170.   whatsit_node,mark_node,ins_node: begin prev_p:=p; p:=link(prev_p);
  16171.     end;
  16172.   glue_node,kern_node,penalty_node: begin q:=p; p:=link(q); link(q):=null;
  16173.     link(prev_p):=p; flush_node_list(q);
  16174.     end;
  16175.   othercases confusion("pruning")
  16176. @:this can't happen pruning}{\quad pruning@>
  16177.   endcases;
  16178. prune_page_top:=link(temp_head);
  16179. @ @<Insert glue for |split_top_skip|...@>=
  16180. begin q:=new_skip_param(split_top_skip_code); link(prev_p):=q; link(q):=p;
  16181.   {now |temp_ptr=glue_ptr(q)|}
  16182. if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
  16183. else width(temp_ptr):=0;
  16184. p:=null;
  16185. @ The next subroutine finds the best place to break a given vertical list
  16186. so as to obtain a box of height~|h|, with maximum depth~|d|.
  16187. A pointer to the beginning of the vertical list is given,
  16188. and a pointer to the optimum breakpoint is returned. The list is effectively
  16189. followed by a forced break, i.e., a penalty node with the |eject_penalty|;
  16190. if the best break occurs at this artificial node, the value |null| is returned.
  16191. An array of six |scaled| distances is used to keep track of the height
  16192. from the beginning of the list to the current place, just as in |line_break|.
  16193. In fact, we use one of the same arrays, only changing its name to reflect
  16194. its new significance.
  16195. @d active_height==active_width {new name for the six distance variables}
  16196. @d cur_height==active_height[1] {the natural height}
  16197. @d set_height_zero(#)==active_height[#]:=0 {initialize the height to zero}
  16198. @d update_heights=90 {go here to record glue in the |active_height| table}
  16199. @p function vert_break(@!p:pointer; @!h,@!d:scaled):pointer;
  16200.   {finds optimum page break}
  16201. label done,not_found,update_heights;
  16202. var prev_p:pointer; {if |p| is a glue node, |type(prev_p)| determines
  16203.   whether |p| is a legal breakpoint}
  16204. @!q,@!r:pointer; {glue specifications}
  16205. @!pi:integer; {penalty value}
  16206. @!b:integer; {badness at a trial breakpoint}
  16207. @!least_cost:integer; {the smallest badness plus penalties found so far}
  16208. @!best_place:pointer; {the most recent break that leads to |least_cost|}
  16209. @!prev_dp:scaled; {depth of previous box in the list}
  16210. @!t:small_number; {|type| of the node following a kern}
  16211. begin prev_p:=p; {an initial glue node is not a legal breakpoint}
  16212. least_cost:=awful_bad; do_all_six(set_height_zero); prev_dp:=0;
  16213. loop@+  begin @<If node |p| is a legal breakpoint, check if this break is
  16214.     the best known, and |goto done| if |p| is null or
  16215.     if the page-so-far is already too full to accept more stuff@>;
  16216.   prev_p:=p; p:=link(prev_p);
  16217.   end;
  16218. done: vert_break:=best_place;
  16219. @ A global variable |best_height_plus_depth| will be set to the natural size
  16220. of the box that corresponds to the optimum breakpoint found by |vert_break|.
  16221. (This value is used by the insertion-splitting algorithm of the page builder.)
  16222. @<Glob...@>=
  16223. @!best_height_plus_depth:scaled; {height of the best box, without stretching or
  16224.   shrinking}
  16225. @ A subtle point to be noted here is that the maximum depth~|d| might be
  16226. negative, so |cur_height| and |prev_dp| might need to be corrected even
  16227. after a glue or kern node.
  16228. @<If node |p| is a legal breakpoint, check...@>=
  16229. if p=null then pi:=eject_penalty
  16230. else  @<Use node |p| to update the current height and depth measurements;
  16231.     if this node is not a legal breakpoint, |goto not_found|
  16232.     or |update_heights|,
  16233.     otherwise set |pi| to the associated penalty at the break@>;
  16234. @<Check if node |p| is a new champion breakpoint; then \(go)|goto done|
  16235.   if |p| is a forced break or if the page-so-far is already too full@>;
  16236. if (type(p)<glue_node)or(type(p)>kern_node) then goto not_found;
  16237. update_heights: @<Update the current height and depth measurements with
  16238.   respect to a glue or kern node~|p|@>;
  16239. not_found: if prev_dp>d then
  16240.     begin cur_height:=cur_height+prev_dp-d;
  16241.     prev_dp:=d;
  16242.     end;
  16243. @ @<Use node |p| to update the current height and depth measurements...@>=
  16244. case type(p) of
  16245. hlist_node,vlist_node,rule_node: begin@t@>@;@/
  16246.   cur_height:=cur_height+prev_dp+height(p); prev_dp:=depth(p);
  16247.   goto not_found;
  16248.   end;
  16249. whatsit_node:@<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
  16250. glue_node: if precedes_break(prev_p) then pi:=0
  16251.   else goto update_heights;
  16252. kern_node: begin if link(p)=null then t:=penalty_node
  16253.   else t:=type(link(p));
  16254.   if t=glue_node then pi:=0@+else goto update_heights;
  16255.   end;
  16256. penalty_node: pi:=penalty(p);
  16257. mark_node,ins_node: goto not_found;
  16258. othercases confusion("vertbreak")
  16259. @:this can't happen vertbreak}{\quad vertbreak@>
  16260. endcases
  16261. @ @d deplorable==100000 {more than |inf_bad|, but less than |awful_bad|}
  16262. @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
  16263. if pi<inf_penalty then
  16264.   begin @<Compute the badness, |b|, using |awful_bad|
  16265.     if the box is too full@>;
  16266.   if b<awful_bad then
  16267.     if pi<=eject_penalty then b:=pi
  16268.     else if b<inf_bad then b:=b+pi
  16269.       else b:=deplorable;
  16270.   if b<=least_cost then
  16271.     begin best_place:=p; least_cost:=b;
  16272.     best_height_plus_depth:=cur_height+prev_dp;
  16273.     end;
  16274.   if (b=awful_bad)or(pi<=eject_penalty) then goto done;
  16275.   end
  16276. @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
  16277. if cur_height<h then
  16278.   if (active_height[3]<>0) or (active_height[4]<>0) or
  16279.     (active_height[5]<>0) then b:=0
  16280.   else b:=badness(h-cur_height,active_height[2])
  16281. else if cur_height-h>active_height[6] then b:=awful_bad
  16282. else b:=badness(cur_height-h,active_height[6])
  16283. @ Vertical lists that are subject to the |vert_break| procedure should not
  16284. contain infinite shrinkability, since that would permit any amount of
  16285. information to ``fit'' on one page.
  16286. @<Update the current height and depth measurements with...@>=
  16287. if type(p)=kern_node then q:=p
  16288. else  begin q:=glue_ptr(p);
  16289.   active_height[2+stretch_order(q)]:=@|
  16290.     active_height[2+stretch_order(q)]+stretch(q);@/
  16291.   active_height[6]:=active_height[6]+shrink(q);
  16292.   if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16293.     begin@t@>@;@/
  16294.     print_err("Infinite glue shrinkage found in box being split");@/
  16295. @.Infinite glue shrinkage...@>
  16296.     help4("The box you are \vsplitting contains some infinitely")@/
  16297.       ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
  16298.       ("Such glue doesn't belong there; but you can safely proceed,")@/
  16299.       ("since the offensive shrinkability has been made finite.");
  16300.     error; r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
  16301.     glue_ptr(p):=r; q:=r;
  16302.     end;
  16303.   end;
  16304. cur_height:=cur_height+prev_dp+width(q); prev_dp:=0
  16305. @ Now we are ready to consider |vsplit| itself. Most of
  16306. its work is accomplished by the two subroutines that we have just considered.
  16307. Given the number of a vlist box |n|, and given a desired page height |h|,
  16308. the |vsplit| function finds the best initial segment of the vlist and
  16309. returns a box for a page of height~|h|. The remainder of the vlist, if
  16310. any, replaces the original box, after removing glue and penalties and
  16311. adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
  16312. set the values of |split_first_mark| and |split_bot_mark|; we use the
  16313. fact that |split_first_mark=null| if and only if |split_bot_mark=null|.
  16314. The original box becomes ``void'' if and only if it has been entirely
  16315. extracted.  The extracted box is ``void'' if and only if the original
  16316. box was void (or if it was, erroneously, an hlist box).
  16317. @p function vsplit(@!n:eight_bits; @!h:scaled):pointer;
  16318.   {extracts a page of height |h| from box |n|}
  16319. label exit,done;
  16320. var v:pointer; {the box to be split}
  16321. p:pointer; {runs through the vlist}
  16322. q:pointer; {points to where the break occurs}
  16323. begin v:=box(n);
  16324. if split_first_mark<>null then
  16325.   begin delete_token_ref(split_first_mark); split_first_mark:=null;
  16326.   delete_token_ref(split_bot_mark); split_bot_mark:=null;
  16327.   end;
  16328. @<Dispense with trivial cases of void or bad boxes@>;
  16329. q:=vert_break(list_ptr(v),h,split_max_depth);
  16330. @<Look at all the marks in nodes before the break, and set the final
  16331.   link to |null| at the break@>;
  16332. q:=prune_page_top(q); p:=list_ptr(v); free_node(v,box_node_size);
  16333. if q=null then box(n):=null {the |eq_level| of the box stays the same}
  16334. else box(n):=vpack(q,natural);
  16335. vsplit:=vpackage(p,h,exactly,split_max_depth);
  16336. exit: end;
  16337. @ @<Dispense with trivial cases of void or bad boxes@>=
  16338. if v=null then
  16339.   begin vsplit:=null; return;
  16340.   end;
  16341. if type(v)<>vlist_node then
  16342.   begin print_err(""); print_esc("vsplit"); print(" needs a ");
  16343.   print_esc("vbox");
  16344. @:vsplit_}{\.{\\vsplit needs a \\vbox}@>
  16345.   help2("The box you are trying to split is an \hbox.")@/
  16346.   ("I can't split such a box, so I'll leave it alone.");
  16347.   error; vsplit:=null; return;
  16348.   end
  16349. @ It's possible that the box begins with a penalty node that is the
  16350. ``best'' break, so we must be careful to handle this special case correctly.
  16351. @<Look at all the marks...@>=
  16352. p:=list_ptr(v);
  16353. if p=q then list_ptr(v):=null
  16354. else loop@+begin if type(p)=mark_node then
  16355.     if split_first_mark=null then
  16356.       begin split_first_mark:=mark_ptr(p);
  16357.       split_bot_mark:=split_first_mark;
  16358.       token_ref_count(split_first_mark):=@|
  16359.         token_ref_count(split_first_mark)+2;
  16360.       end
  16361.     else  begin delete_token_ref(split_bot_mark);
  16362.       split_bot_mark:=mark_ptr(p);
  16363.       add_token_ref(split_bot_mark);
  16364.       end;
  16365.   if link(p)=q then
  16366.     begin link(p):=null; goto done;
  16367.     end;
  16368.   p:=link(p);
  16369.   end;
  16370. done:
  16371. @* \[45] The page builder.
  16372. When \TeX\ appends new material to its main vlist in vertical mode, it uses
  16373. a method something like |vsplit| to decide where a page ends, except that
  16374. the calculations are done ``on line'' as new items come in.
  16375. The main complication in this process is that insertions must be put
  16376. into their boxes and removed from the vlist, in a more-or-less optimum manner.
  16377. We shall use the term ``current page'' for that part of the main vlist that
  16378. is being considered as a candidate for being broken off and sent to the
  16379. user's output routine. The current page starts at |link(page_head)|, and
  16380. it ends at |page_tail|.  We have |page_head=page_tail| if this list is empty.
  16381. @^current page@>
  16382. Utter chaos would reign if the user kept changing page specifications
  16383. while a page is being constructed, so the page builder keeps the pertinent
  16384. specifications frozen as soon as the page receives its first box or
  16385. insertion.  The global variable |page_contents| is |empty| when the
  16386. current page contains only mark nodes and content-less whatsit nodes; it
  16387. is |inserts_only| if the page contains only insertion nodes in addition to
  16388. marks and whatsits.  Glue nodes, kern nodes, and penalty nodes are
  16389. discarded until a box or rule node appears, at which time |page_contents|
  16390. changes to |box_there|.  As soon as |page_contents| becomes non-|empty|,
  16391. the current |vsize| and |max_depth| are squirreled away into |page_goal|
  16392. and |page_max_depth|; the latter values will be used until the page has
  16393. been forwarded to the user's output routine. The \.{\\topskip} adjustment
  16394. is made when |page_contents| changes to |box_there|.
  16395. Although |page_goal| starts out equal to |vsize|, it is decreased by the
  16396. scaled natural height-plus-depth of the insertions considered so far, and by
  16397. the \.{\\skip} corrections for those insertions. Therefore it represents
  16398. the size into which the non-inserted material should fit, assuming that
  16399. all insertions in the current page have been made.
  16400. The global variables |best_page_break| and |least_page_cost| correspond
  16401. respectively to the local variables |best_place| and |least_cost| in the
  16402. |vert_break| routine that we have already studied; i.e., they record the
  16403. location and value of the best place currently known for breaking the
  16404. current page. The value of |page_goal| at the time of the best break is
  16405. stored in |best_size|.
  16406. @d inserts_only=1
  16407.   {|page_contents| when an insert node has been contributed, but no boxes}
  16408. @d box_there=2 {|page_contents| when a box or rule has been contributed}
  16409. @<Glob...@>=
  16410. @!page_tail:pointer; {the final node on the current page}
  16411. @!page_contents:empty..box_there; {what is on the current page so far?}
  16412. @!page_max_depth:scaled; {maximum box depth on page being built}
  16413. @!best_page_break:pointer; {break here to get the best page known so far}
  16414. @!least_page_cost:integer; {the score for this currently best page}
  16415. @!best_size:scaled; {its |page_goal|}
  16416. @ The page builder has another data structure to keep track of insertions.
  16417. This is a list of four-word nodes, starting and ending at |page_ins_head|.
  16418. That is, the first element of the list is node |r@t$_1$@>=link(page_ins_head)|;
  16419. node $r_j$ is followed by |r@t$_{j+1}$@>=link(r@t$_j$@>)|; and if there are
  16420. |n| items we have |r@t$_{n+1}$@>=page_ins_head|. The |subtype| field of
  16421. each node in this list refers to an insertion number; for example, `\.{\\insert
  16422. 250}' would correspond to a node whose |subtype| is |qi(250)|
  16423. (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
  16424. fields are in increasing order, and |subtype(page_ins_head)=
  16425. qi(255)|, so |page_ins_head| serves as a convenient sentinel
  16426. at the end of the list. A record is present for each insertion number that
  16427. appears in the current page.
  16428. The |type| field in these nodes distinguishes two possibilities that
  16429. might occur as we look ahead before deciding on the optimum page break.
  16430. If |type(r)=inserting|, then |height(r)| contains the total of the
  16431. height-plus-depth dimensions of the box and all its inserts seen so far.
  16432. If |type(r)=split_up|, then no more insertions will be made into this box,
  16433. because at least one previous insertion was too big to fit on the current
  16434. page; |broken_ptr(r)| points to the node where that insertion will be
  16435. split, if \TeX\ decides to split it, |broken_ins(r)| points to the
  16436. insertion node that was tentatively split, and |height(r)| includes also the
  16437. natural height plus depth of the part that would be split off.
  16438. In both cases, |last_ins_ptr(r)| points to the last |ins_node|
  16439. encountered for box |qo(subtype(r))| that would be at least partially
  16440. inserted on the next page; and |best_ins_ptr(r)| points to the last
  16441. such |ins_node| that should actually be inserted, to get the page with
  16442. minimum badness among all page breaks considered so far. We have
  16443. |best_ins_ptr(r)=null| if and only if no insertion for this box should
  16444. be made to produce this optimum page.
  16445. The data structure definitions here use the fact that the |@!height| field
  16446. appears in the fourth word of a box node.
  16447. @^data structure assumptions@>
  16448. @d page_ins_node_size=4 {number of words for a page insertion node}
  16449. @d inserting=0 {an insertion class that has not yet overflowed}
  16450. @d split_up=1 {an overflowed insertion class}
  16451. @d broken_ptr(#)==link(#+1)
  16452.   {an insertion for this class will break here if anywhere}
  16453. @d broken_ins(#)==info(#+1) {this insertion might break at |broken_ptr|}
  16454. @d last_ins_ptr(#)==link(#+2) {the most recent insertion for this |subtype|}
  16455. @d best_ins_ptr(#)==info(#+2) {the optimum most recent insertion}
  16456. @<Initialize the special list heads...@>=
  16457. subtype(page_ins_head):=qi(255);
  16458. type(page_ins_head):=split_up; link(page_ins_head):=page_ins_head;
  16459. @ An array |page_so_far| records the heights and depths of everything
  16460. on the current page. This array contains six |scaled| numbers, like the
  16461. similar arrays already considered in |line_break| and |vert_break|; and it
  16462. also contains |page_goal| and |page_depth|, since these values are
  16463. all accessible to the user via |set_page_dimen| commands. The
  16464. value of |page_so_far[1]| is also called |page_total|.  The stretch
  16465. and shrink components of the \.{\\skip} corrections for each insertion are
  16466. included in |page_so_far|, but the natural space components of these
  16467. corrections are not, since they have been subtracted from |page_goal|.
  16468. The variable |page_depth| records the depth of the current page; it has been
  16469. adjusted so that it is at most |page_max_depth|. The variable
  16470. |last_glue| points to the glue specification of the most recent node
  16471. contributed from the contribution list, if this was a glue node; otherwise
  16472. |last_glue=max_halfword|. (If the contribution list is nonempty,
  16473. however, the value of |last_glue| is not necessarily accurate.)
  16474. The variables |last_penalty| and |last_kern| are similar.  And
  16475. finally, |insert_penalties| holds the sum of the penalties associated with
  16476. all split and floating insertions.
  16477. @d page_goal==page_so_far[0] {desired height of information on page being built}
  16478. @d page_total==page_so_far[1] {height of the current page}
  16479. @d page_shrink==page_so_far[6] {shrinkability of the current page}
  16480. @d page_depth==page_so_far[7] {depth of the current page}
  16481. @<Glob...@>=
  16482. @!page_so_far:array [0..7] of scaled; {height and glue of the current page}
  16483. @!last_glue:pointer; {used to implement \.{\\lastskip}}
  16484. @!last_penalty:integer; {used to implement \.{\\lastpenalty}}
  16485. @!last_kern:scaled; {used to implement \.{\\lastkern}}
  16486. @!insert_penalties:integer; {sum of the penalties for held-over insertions}
  16487. @ @<Put each...@>=
  16488. primitive("pagegoal",set_page_dimen,0);
  16489. @!@:page_goal_}{\.{\\pagegoal} primitive@>
  16490. primitive("pagetotal",set_page_dimen,1);
  16491. @!@:page_total_}{\.{\\pagetotal} primitive@>
  16492. primitive("pagestretch",set_page_dimen,2);
  16493. @!@:page_stretch_}{\.{\\pagestretch} primitive@>
  16494. primitive("pagefilstretch",set_page_dimen,3);
  16495. @!@:page_fil_stretch_}{\.{\\pagefilstretch} primitive@>
  16496. primitive("pagefillstretch",set_page_dimen,4);
  16497. @!@:page_fill_stretch_}{\.{\\pagefillstretch} primitive@>
  16498. primitive("pagefilllstretch",set_page_dimen,5);
  16499. @!@:page_filll_stretch_}{\.{\\pagefilllstretch} primitive@>
  16500. primitive("pageshrink",set_page_dimen,6);
  16501. @!@:page_shrink_}{\.{\\pageshrink} primitive@>
  16502. primitive("pagedepth",set_page_dimen,7);
  16503. @!@:page_depth_}{\.{\\pagedepth} primitive@>
  16504. @ @<Cases of |print_cmd_chr|...@>=
  16505. set_page_dimen: case chr_code of
  16506. 0: print_esc("pagegoal");
  16507. 1: print_esc("pagetotal");
  16508. 2: print_esc("pagestretch");
  16509. 3: print_esc("pagefilstretch");
  16510. 4: print_esc("pagefillstretch");
  16511. 5: print_esc("pagefilllstretch");
  16512. 6: print_esc("pageshrink");
  16513. othercases print_esc("pagedepth")
  16514. endcases;
  16515. @ @d print_plus_end(#)==print(#);@+end
  16516. @d print_plus(#)==if page_so_far[#]<>0 then
  16517.   begin print(" plus "); print_scaled(page_so_far[#]); print_plus_end
  16518. @p procedure print_totals;
  16519. begin print_scaled(page_total);
  16520. print_plus(2)("");
  16521. print_plus(3)("fil");
  16522. print_plus(4)("fill");
  16523. print_plus(5)("filll");
  16524. if page_shrink<>0 then
  16525.   begin print(" minus "); print_scaled(page_shrink);
  16526.   end;
  16527. @ @<Show the status of the current page@>=
  16528. if page_head<>page_tail then
  16529.   begin print_nl("### current page:");
  16530.   if output_active then print(" (held over for next output)");
  16531. @.held over for next output@>
  16532.   show_box(link(page_head));
  16533.   if page_contents>empty then
  16534.     begin print_nl("total height "); print_totals;
  16535. @:total_height}{\.{total height}@>
  16536.     print_nl(" goal height "); print_scaled(page_goal);
  16537. @.goal height@>
  16538.     r:=link(page_ins_head);
  16539.     while r<>page_ins_head do
  16540.       begin print_ln; print_esc("insert"); t:=qo(subtype(r));
  16541.       print_int(t); print(" adds ");
  16542.       t:=x_over_n(height(r),1000)*count(t); print_scaled(t);
  16543.       if type(r)=split_up then
  16544.         begin q:=page_head; t:=0;
  16545.         repeat q:=link(q);
  16546.         if (type(q)=ins_node)and(subtype(q)=subtype(r)) then incr(t);
  16547.         until q=broken_ins(r);
  16548.         print(", #"); print_int(t); print(" might split");
  16549.         end;
  16550.       r:=link(r);
  16551.       end;
  16552.     end;
  16553.   end
  16554. @ Here is a procedure that is called when the |page_contents| is changing
  16555. from |empty| to |inserts_only| or |box_there|.
  16556. @d set_page_so_far_zero(#)==page_so_far[#]:=0
  16557. @p procedure freeze_page_specs(@!s:small_number);
  16558. begin page_contents:=s;
  16559. page_goal:=vsize; page_max_depth:=max_depth;
  16560. page_depth:=0; do_all_six(set_page_so_far_zero);
  16561. least_page_cost:=awful_bad;
  16562. @!stat if tracing_pages>0 then
  16563.   begin begin_diagnostic;
  16564.   print_nl("%% goal height="); print_scaled(page_goal);
  16565. @.goal height@>
  16566.   print(", max depth="); print_scaled(page_max_depth);
  16567.   end_diagnostic(false);
  16568.   end;@;@+tats@;@/
  16569. @ Pages are built by appending nodes to the current list in \TeX's
  16570. vertical mode, which is at the outermost level of the semantic nest. This
  16571. vlist is split into two parts; the ``current page'' that we have been
  16572. talking so much about already, and the ``contribution list'' that receives
  16573. new nodes as they are created.  The current page contains everything that
  16574. the page builder has accounted for in its data structures, as described
  16575. above, while the contribution list contains other things that have been
  16576. generated by other parts of \TeX\ but have not yet been
  16577. seen by the page builder.
  16578. The contribution list starts at |link(contrib_head)|, and it ends at the
  16579. current node in \TeX's vertical mode.
  16580. When \TeX\ has appended new material in vertical mode, it calls the procedure
  16581. |build_page|, which tries to catch up by moving nodes from the contribution
  16582. list to the current page. This procedure will succeed in its goal of
  16583. emptying the contribution list, unless a page break is discovered, i.e.,
  16584. unless the current page has grown to the point where the optimum next
  16585. page break has been determined. In the latter case, the nodes after the
  16586. optimum break will go back onto the contribution list, and control will
  16587. effectively pass to the user's output routine.
  16588. We make |type(page_head)=glue_node|, so that an initial glue node on
  16589. the current page will not be considered a valid breakpoint.
  16590. @<Initialize the special list...@>=
  16591. type(page_head):=glue_node; subtype(page_head):=normal;
  16592. @ The global variable |output_active| is true during the time the
  16593. user's output routine is driving \TeX.
  16594. @<Glob...@>=
  16595. @!output_active:boolean; {are we in the midst of an output routine?}
  16596. @ @<Set init...@>=
  16597. output_active:=false; insert_penalties:=0;
  16598. @ The page builder is ready to start a fresh page if we initialize
  16599. the following state variables. (However, the page insertion list is initialized
  16600. elsewhere.)
  16601. @<Start a new current page@>=
  16602. page_contents:=empty; page_tail:=page_head; link(page_head):=null;@/
  16603. last_glue:=max_halfword; last_penalty:=0; last_kern:=0;
  16604. page_depth:=0; page_max_depth:=0
  16605. @ At certain times box 255 is supposed to be void (i.e., |null|),
  16606. or an insertion box is supposed to be ready to accept a vertical list.
  16607. If not, an error message is printed, and the following subroutine
  16608. flushes the unwanted contents, reporting them to the user.
  16609. @p procedure box_error(@!n:eight_bits);
  16610. begin error; begin_diagnostic;
  16611. print_nl("The following box has been deleted:");
  16612. @.The following...deleted@>
  16613. show_box(box(n)); end_diagnostic(true);
  16614. flush_node_list(box(n)); box(n):=null;
  16615. @ The following procedure guarantees that a given box register
  16616. does not contain an \.{\\hbox}.
  16617. @p procedure ensure_vbox(@!n:eight_bits);
  16618. var p:pointer; {the box register contents}
  16619. begin p:=box(n);
  16620. if p<>null then if type(p)=hlist_node then
  16621.   begin print_err("Insertions can only be added to a vbox");
  16622. @.Insertions can only...@>
  16623.   help3("Tut tut: You're trying to \insert into a")@/
  16624.     ("\box register that now contains an \hbox.")@/
  16625.     ("Proceed, and I'll discard its present contents.");
  16626.   box_error(n);
  16627.   end;
  16628. @ \TeX\ is not always in vertical mode at the time |build_page|
  16629. is called; the current mode reflects what \TeX\ should return to, after
  16630. the contribution list has been emptied. A call on |build_page| should
  16631. be immediately followed by `|goto big_switch|', which is \TeX's central
  16632. control point.
  16633. @d contribute=80 {go here to link a node into the current page}
  16634. @p @t\4@>@<Declare the procedure called |fire_up|@>@;@/
  16635. procedure build_page; {append contributions to the current page}
  16636. label exit,done,done1,continue,contribute,update_heights;
  16637. var p:pointer; {the node being appended}
  16638. @!q,@!r:pointer; {nodes being examined}
  16639. @!b,@!c:integer; {badness and cost of current page}
  16640. @!pi:integer; {penalty to be added to the badness}
  16641. @!n:min_quarterword..255; {insertion box number}
  16642. @!delta,@!h,@!w:scaled; {sizes used for insertion calculations}
  16643. begin if (link(contrib_head)=null)or output_active then return;
  16644. repeat continue: p:=link(contrib_head);@/
  16645. @<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
  16646. @<Move node |p| to the current page; if it is time for a page break,
  16647.   put the nodes following the break back onto the contribution list,
  16648.   and |return| to the user's output routine if there is one@>;
  16649. until link(contrib_head)=null;
  16650. @<Make the contribution list empty by setting its tail to |contrib_head|@>;
  16651. exit:end;
  16652. @ @d contrib_tail==nest[0].tail_field {tail of the contribution list}
  16653. @<Make the contribution list empty...@>=
  16654. if nest_ptr=0 then tail:=contrib_head {vertical mode}
  16655. else contrib_tail:=contrib_head {other modes}
  16656. @ @<Update the values of |last_glue|...@>=
  16657. if last_glue<>max_halfword then delete_glue_ref(last_glue);
  16658. last_penalty:=0; last_kern:=0;
  16659. if type(p)=glue_node then
  16660.   begin last_glue:=glue_ptr(p); add_glue_ref(last_glue);
  16661.   end
  16662. else  begin last_glue:=max_halfword;
  16663.   if type(p)=penalty_node then last_penalty:=penalty(p)
  16664.   else if type(p)=kern_node then last_kern:=width(p);
  16665.   end
  16666. @ The code here is an example of a many-way switch into routines that
  16667. merge together in different places. Some people call this unstructured
  16668. programming, but the author doesn't see much wrong with it, as long as
  16669. @^Knuth, Donald Ervin@>
  16670. the various labels have a well-understood meaning.
  16671. @<Move node |p| to the current page; ...@>=
  16672. @<If the current page is empty and node |p| is to be deleted, |goto done1|;
  16673.   otherwise use node |p| to update the state of the current page;
  16674.   if this node is an insertion, |goto contribute|; otherwise if this node
  16675.   is not a legal breakpoint, |goto contribute| or |update_heights|;
  16676.   otherwise set |pi| to the penalty associated with this breakpoint@>;
  16677. @<Check if node |p| is a new champion breakpoint; then \(if)if it is time for
  16678.   a page break, prepare for output, and either fire up the user's
  16679.   output routine and |return| or ship out the page and |goto done|@>;
  16680. if (type(p)<glue_node)or(type(p)>kern_node) then goto contribute;
  16681. update_heights:@<Update the current page measurements with respect to the
  16682.   glue or kern specified by node~|p|@>;
  16683. contribute: @<Make sure that |page_max_depth| is not exceeded@>;
  16684. @<Link node |p| into the current page and |goto done|@>;
  16685. done1:@<Recycle node |p|@>;
  16686. done:
  16687. @ @<Link node |p| into the current page and |goto done|@>=
  16688. link(page_tail):=p; page_tail:=p;
  16689. link(contrib_head):=link(p); link(p):=null; goto done
  16690. @ @<Recycle node |p|@>=
  16691. link(contrib_head):=link(p); link(p):=null; flush_node_list(p)
  16692. @ The title of this section is already so long, it seems best to avoid
  16693. making it more accurate but still longer, by mentioning the fact that a
  16694. kern node at the end of the contribution list will not be contributed until
  16695. we know its successor.
  16696. @<If the current page is empty...@>=
  16697. case type(p) of
  16698. hlist_node,vlist_node,rule_node: if page_contents<box_there then
  16699.     @<Initialize the current page, insert the \.{\\topskip} glue
  16700.       ahead of |p|, and |goto continue|@>
  16701.   else @<Prepare to move a box or rule node to the current page,
  16702.     then |goto contribute|@>;
  16703. whatsit_node: @<Prepare to move whatsit |p| to the current page,
  16704.   then |goto contribute|@>;
  16705. glue_node: if page_contents<box_there then goto done1
  16706.   else if precedes_break(page_tail) then pi:=0
  16707.   else goto update_heights;
  16708. kern_node: if page_contents<box_there then goto done1
  16709.   else if link(p)=null then return
  16710.   else if type(link(p))=glue_node then pi:=0
  16711.   else goto update_heights;
  16712. penalty_node: if page_contents<box_there then goto done1@+else pi:=penalty(p);
  16713. mark_node: goto contribute;
  16714. ins_node: @<Append an insertion to the current page and |goto contribute|@>;
  16715. othercases confusion("page")
  16716. @:this can't happen page}{\quad page@>
  16717. endcases
  16718. @ @<Initialize the current page, insert the \.{\\topskip} glue...@>=
  16719. begin if page_contents=empty then freeze_page_specs(box_there)
  16720. else page_contents:=box_there;
  16721. q:=new_skip_param(top_skip_code); {now |temp_ptr=glue_ptr(q)|}
  16722. if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
  16723. else width(temp_ptr):=0;
  16724. link(q):=p; link(contrib_head):=q; goto continue;
  16725. @ @<Prepare to move a box or rule node to the current page...@>=
  16726. begin page_total:=page_total+page_depth+height(p);
  16727. page_depth:=depth(p);
  16728. goto contribute;
  16729. @ @<Make sure that |page_max_depth| is not exceeded@>=
  16730. if page_depth>page_max_depth then
  16731.   begin page_total:=@|
  16732.     page_total+page_depth-page_max_depth;@/
  16733.   page_depth:=page_max_depth;
  16734.   end;
  16735. @ @<Update the current page measurements with respect to the glue...@>=
  16736. if type(p)=kern_node then q:=p
  16737. else begin q:=glue_ptr(p);
  16738.   page_so_far[2+stretch_order(q)]:=@|
  16739.     page_so_far[2+stretch_order(q)]+stretch(q);@/
  16740.   page_shrink:=page_shrink+shrink(q);
  16741.   if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16742.     begin@t@>@;@/
  16743.     print_err("Infinite glue shrinkage found on current page");@/
  16744. @.Infinite glue shrinkage...@>
  16745.     help4("The page about to be output contains some infinitely")@/
  16746.       ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
  16747.       ("Such glue doesn't belong there; but you can safely proceed,")@/
  16748.       ("since the offensive shrinkability has been made finite.");
  16749.     error;
  16750.     r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
  16751.     glue_ptr(p):=r; q:=r;
  16752.     end;
  16753.   end;
  16754. page_total:=page_total+page_depth+width(q); page_depth:=0
  16755. @ @<Check if node |p| is a new champion breakpoint; then \(if)...@>=
  16756. if pi<inf_penalty then
  16757.   begin @<Compute the badness, |b|, of the current page,
  16758.     using |awful_bad| if the box is too full@>;
  16759.   if b<awful_bad then
  16760.     if pi<=eject_penalty then c:=pi
  16761.     else  if b<inf_bad then c:=b+pi+insert_penalties
  16762.       else c:=deplorable
  16763.   else c:=b;
  16764.   if insert_penalties>=10000 then c:=awful_bad;
  16765.   @!stat if tracing_pages>0 then @<Display the page break cost@>;@+tats@;@/
  16766.   if c<=least_page_cost then
  16767.     begin best_page_break:=p; best_size:=page_goal;
  16768.     least_page_cost:=c;
  16769.     r:=link(page_ins_head);
  16770.     while r<>page_ins_head do
  16771.       begin best_ins_ptr(r):=last_ins_ptr(r);
  16772.       r:=link(r);
  16773.       end;
  16774.     end;
  16775.   if (c=awful_bad)or(pi<=eject_penalty) then
  16776.     begin fire_up(p); {output the current page at the best place}
  16777.     if output_active then return; {user's output routine will act}
  16778.     goto done; {the page has been shipped out by default output routine}
  16779.     end;
  16780.   end
  16781. @ @<Display the page break cost@>=
  16782. begin begin_diagnostic; print_nl("%");
  16783. print(" t="); print_totals;@/
  16784. print(" g="); print_scaled(page_goal);@/
  16785. print(" b=");
  16786. if b=awful_bad then print_char("*")@+else print_int(b);
  16787. @.*\relax@>
  16788. print(" p="); print_int(pi);
  16789. print(" c=");
  16790. if c=awful_bad then print_char("*")@+else print_int(c);
  16791. if c<=least_page_cost then print_char("#");
  16792. end_diagnostic(false);
  16793. @ @<Compute the badness, |b|, of the current page...@>=
  16794. if page_total<page_goal then
  16795.   if (page_so_far[3]<>0) or (page_so_far[4]<>0) or@|
  16796.     (page_so_far[5]<>0) then b:=0
  16797.   else b:=badness(page_goal-page_total,page_so_far[2])
  16798. else if page_total-page_goal>page_shrink then b:=awful_bad
  16799. else b:=badness(page_total-page_goal,page_shrink)
  16800. @ @<Append an insertion to the current page and |goto contribute|@>=
  16801. begin if page_contents=empty then freeze_page_specs(inserts_only);
  16802. n:=subtype(p); r:=page_ins_head;
  16803. while n>=subtype(link(r)) do r:=link(r);
  16804. n:=qo(n);
  16805. if subtype(r)<>qi(n) then
  16806.   @<Create a page insertion node with |subtype(r)=qi(n)|, and
  16807.     include the glue correction for box |n| in the
  16808.     current page state@>;
  16809. if type(r)=split_up then insert_penalties:=insert_penalties+float_cost(p)
  16810. else  begin last_ins_ptr(r):=p;
  16811.   delta:=page_goal-page_total-page_depth+page_shrink;
  16812.     {this much room is left if we shrink the maximum}
  16813.   if count(n)=1000 then h:=height(p)
  16814.   else h:=x_over_n(height(p),1000)*count(n); {this much room is needed}
  16815.   if ((h<=0)or(h<=delta))and(height(p)+height(r)<=dimen(n)) then
  16816.     begin page_goal:=page_goal-h; height(r):=height(r)+height(p);
  16817.     end
  16818.   else @<Find the best way to split the insertion, and change
  16819.     |type(r)| to |split_up|@>;
  16820.   end;
  16821. goto contribute;
  16822. @ We take note of the value of \.{\\skip} |n| and the height plus depth
  16823. of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
  16824. encountered for a new page. A user who changes the contents of \.{\\box}~|n|
  16825. after that first \.{\\insert}~|n| had better be either extremely careful
  16826. or extremely lucky, or both.
  16827. @<Create a page insertion node...@>=
  16828. begin q:=get_node(page_ins_node_size); link(q):=link(r); link(r):=q; r:=q;
  16829. subtype(r):=qi(n); type(r):=inserting; ensure_vbox(n);
  16830. if box(n)=null then height(r):=0
  16831. else height(r):=height(box(n))+depth(box(n));
  16832. best_ins_ptr(r):=null;@/
  16833. q:=skip(n);
  16834. if count(n)=1000 then h:=height(r)
  16835. else h:=x_over_n(height(r),1000)*count(n);
  16836. page_goal:=page_goal-h-width(q);@/
  16837. page_so_far[2+stretch_order(q)]:=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
  16838. page_shrink:=page_shrink+shrink(q);
  16839. if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16840.   begin print_err("Infinite glue shrinkage inserted from "); print_esc("skip");
  16841. @.Infinite glue shrinkage...@>
  16842.   print_int(n);
  16843.   help3("The correction glue for page breaking with insertions")@/
  16844.     ("must have finite shrinkability. But you may proceed,")@/
  16845.     ("since the offensive shrinkability has been made finite.");
  16846.   error;
  16847.   end;
  16848. @ Here is the code that will split a long footnote between pages, in an
  16849. emergency. The current situation deserves to be recapitulated: Node |p|
  16850. is an insertion into box |n|; the insertion will not fit, in its entirety,
  16851. either because it would make the total contents of box |n| greater than
  16852. \.{\\dimen} |n|, or because it would make the incremental amount of growth
  16853. |h| greater than the available space |delta|, or both. (This amount |h| has
  16854. been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
  16855. over 1000.) Now we will choose the best way to break the vlist of the
  16856. insertion, using the same criteria as in the \.{\\vsplit} operation.
  16857. @<Find the best way to split the insertion...@>=
  16858. begin if count(n)<=0 then w:=max_dimen
  16859. else  begin w:=page_goal-page_total-page_depth;
  16860.   if count(n)<>1000 then w:=x_over_n(w,count(n))*1000;
  16861.   end;
  16862. if w>dimen(n)-height(r) then w:=dimen(n)-height(r);
  16863. q:=vert_break(ins_ptr(p),w,depth(p));
  16864. height(r):=height(r)+best_height_plus_depth;
  16865. @!stat if tracing_pages>0 then @<Display the insertion split cost@>;@+tats@;@/
  16866. if count(n)<>1000 then
  16867.   best_height_plus_depth:=x_over_n(best_height_plus_depth,1000)*count(n);
  16868. page_goal:=page_goal-best_height_plus_depth;
  16869. type(r):=split_up; broken_ptr(r):=q; broken_ins(r):=p;
  16870. if q=null then insert_penalties:=insert_penalties+eject_penalty
  16871. else if type(q)=penalty_node then insert_penalties:=insert_penalties+penalty(q);
  16872. @ @<Display the insertion split cost@>=
  16873. begin begin_diagnostic; print_nl("% split"); print_int(n);
  16874. @.split@>
  16875. print(" to "); print_scaled(w);
  16876. print_char(","); print_scaled(best_height_plus_depth);@/
  16877. print(" p=");
  16878. if q=null then print_int(eject_penalty)
  16879. else if type(q)=penalty_node then print_int(penalty(q))
  16880. else print_char("0");
  16881. end_diagnostic(false);
  16882. @ When the page builder has looked at as much material as could appear before
  16883. the next page break, it makes its decision. The break that gave minimum
  16884. badness will be used to put a completed ``page'' into box 255, with insertions
  16885. appended to their other boxes.
  16886. We also set the values of |top_mark|, |first_mark|, and |bot_mark|. The
  16887. program uses the fact that |bot_mark<>null| implies |first_mark<>null|;
  16888. it also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
  16889. The |fire_up| subroutine prepares to output the current page at the best
  16890. place; then it fires up the user's output routine, if there is one,
  16891. or it simply ships out the page. There is one parameter, |c|, which represents
  16892. the node that was being contributed to the page when the decision to
  16893. force an output was made.
  16894. @<Declare the procedure called |fire_up|@>=
  16895. procedure fire_up(@!c:pointer);
  16896. label exit;
  16897. var p,@!q,@!r,@!s:pointer; {nodes being examined and/or changed}
  16898. @!prev_p:pointer; {predecessor of |p|}
  16899. @!n:min_quarterword..255; {insertion box number}
  16900. @!wait:boolean; {should the present insertion be held over?}
  16901. @!save_vbadness:integer; {saved value of |vbadness|}
  16902. @!save_vfuzz: scaled; {saved value of |vfuzz|}
  16903. @!save_split_top_skip: pointer; {saved value of |split_top_skip|}
  16904. begin @<Set the value of |output_penalty|@>;
  16905. if bot_mark<>null then
  16906.   begin if top_mark<>null then delete_token_ref(top_mark);
  16907.   top_mark:=bot_mark; add_token_ref(top_mark);
  16908.   delete_token_ref(first_mark); first_mark:=null;
  16909.   end;
  16910. @<Put the \(o)optimal current page into box 255, update |first_mark| and
  16911.   |bot_mark|, append insertions to their boxes, and put the
  16912.   remaining nodes back on the contribution list@>;
  16913. if (top_mark<>null)and(first_mark=null) then
  16914.   begin first_mark:=top_mark; add_token_ref(top_mark);
  16915.   end;
  16916. if output_routine<>null then
  16917.   if dead_cycles>=max_dead_cycles then
  16918.     @<Explain that too many dead cycles have occurred in a row@>
  16919.   else @<Fire up the user's output routine and |return|@>;
  16920. @<Perform the default output routine@>;
  16921. exit:end;
  16922. @ @<Set the value of |output_penalty|@>=
  16923. if type(best_page_break)=penalty_node then
  16924.   begin geq_word_define(int_base+output_penalty_code,penalty(best_page_break));
  16925.   penalty(best_page_break):=inf_penalty;
  16926.   end
  16927. else geq_word_define(int_base+output_penalty_code,inf_penalty)
  16928. @ As the page is finally being prepared for output,
  16929. pointer |p| runs through the vlist, with |prev_p| trailing behind;
  16930. pointer |q| is the tail of a list of insertions that
  16931. are being held over for a subsequent page.
  16932. @<Put the \(o)optimal current page into box 255...@>=
  16933. if c=best_page_break then best_page_break:=null; {|c| not yet linked in}
  16934. @<Ensure that box 255 is empty before output@>;
  16935. insert_penalties:=0; {this will count the number of insertions held over}
  16936. save_split_top_skip:=split_top_skip;
  16937. if holding_inserts<=0 then
  16938.   @<Prepare all the boxes involved in insertions to act as queues@>;
  16939. q:=hold_head; link(q):=null; prev_p:=page_head; p:=link(prev_p);
  16940. while p<>best_page_break do
  16941.   begin if type(p)=ins_node then
  16942.     begin if holding_inserts<=0 then
  16943.        @<Either insert the material specified by node |p| into the
  16944.          appropriate box, or hold it for the next page;
  16945.          also delete node |p| from the current page@>;
  16946.     end
  16947.   else if type(p)=mark_node then @<Update the values of
  16948.     |first_mark| and |bot_mark|@>;
  16949.   prev_p:=p; p:=link(prev_p);
  16950.   end;
  16951. split_top_skip:=save_split_top_skip;
  16952. @<Break the current page at node |p|, put it in box~255,
  16953.   and put the remaining nodes on the contribution list@>;
  16954. @<Delete \(t)the page-insertion nodes@>
  16955. @ @<Ensure that box 255 is empty before output@>=
  16956. if box(255)<>null then
  16957.   begin print_err(""); print_esc("box"); print("255 is not void");
  16958. @:box255}{\.{\\box255 is not void}@>
  16959.   help2("You shouldn't use \box255 except in \output routines.")@/
  16960.     ("Proceed, and I'll discard its present contents.");
  16961.   box_error(255);
  16962.   end
  16963. @ @<Update the values of |first_mark| and |bot_mark|@>=
  16964. begin if first_mark=null then
  16965.   begin first_mark:=mark_ptr(p);
  16966.   add_token_ref(first_mark);
  16967.   end;
  16968. if bot_mark<>null then delete_token_ref(bot_mark);
  16969. bot_mark:=mark_ptr(p); add_token_ref(bot_mark);
  16970. @ When the following code is executed, the current page runs from node
  16971. |link(page_head)| to node |prev_p|, and the nodes from |p| to |page_tail|
  16972. are to be placed back at the front of the contribution list. Furthermore
  16973. the heldover insertions appear in a list from |link(hold_head)| to |q|; we
  16974. will put them into the current page list for safekeeping while the user's
  16975. output routine is active.  We might have |q=hold_head|; and |p=null| if
  16976. and only if |prev_p=page_tail|. Error messages are suppressed within
  16977. |vpackage|, since the box might appear to be overfull or underfull simply
  16978. because the stretch and shrink from the \.{\\skip} registers for inserts
  16979. are not actually present in the box.
  16980. @<Break the current page at node |p|, put it...@>=
  16981. if p<>null then
  16982.   begin if link(contrib_head)=null then
  16983.     if nest_ptr=0 then tail:=page_tail
  16984.     else contrib_tail:=page_tail;
  16985.   link(page_tail):=link(contrib_head);
  16986.   link(contrib_head):=p;
  16987.   link(prev_p):=null;
  16988.   end;
  16989. save_vbadness:=vbadness; vbadness:=inf_bad;
  16990. save_vfuzz:=vfuzz; vfuzz:=max_dimen; {inhibit error messages}
  16991. box(255):=vpackage(link(page_head),best_size,exactly,page_max_depth);
  16992. vbadness:=save_vbadness; vfuzz:=save_vfuzz;
  16993. if last_glue<>max_halfword then delete_glue_ref(last_glue);
  16994. @<Start a new current page@>; {this sets |last_glue:=max_halfword|}
  16995. if q<>hold_head then
  16996.   begin link(page_head):=link(hold_head); page_tail:=q;
  16997.   end
  16998. @ If many insertions are supposed to go into the same box, we want to know
  16999. the position of the last node in that box, so that we don't need to waste time
  17000. when linking further information into it. The |last_ins_ptr| fields of the
  17001. page insertion nodes are therefore used for this purpose during the
  17002. packaging phase.
  17003. @<Prepare all the boxes involved in insertions to act as queues@>=
  17004. begin r:=link(page_ins_head);
  17005. while r<>page_ins_head do
  17006.   begin if best_ins_ptr(r)<>null then
  17007.     begin n:=qo(subtype(r)); ensure_vbox(n);
  17008.     if box(n)=null then box(n):=new_null_box;
  17009.     p:=box(n)+list_offset;
  17010.     while link(p)<>null do p:=link(p);
  17011.     last_ins_ptr(r):=p;
  17012.     end;
  17013.   r:=link(r);
  17014.   end;
  17015. @ @<Delete \(t)the page-insertion nodes@>=
  17016. r:=link(page_ins_head);
  17017. while r<>page_ins_head do
  17018.   begin q:=link(r); free_node(r,page_ins_node_size); r:=q;
  17019.   end;
  17020. link(page_ins_head):=page_ins_head
  17021. @ We will set |best_ins_ptr:=null| and package the box corresponding to
  17022. insertion node~|r|, just after making the final insertion into that box.
  17023. If this final insertion is `|split_up|', the remainder after splitting
  17024. and pruning (if any) will be carried over to the next page.
  17025. @<Either insert the material specified by node |p| into...@>=
  17026. begin r:=link(page_ins_head);
  17027. while subtype(r)<>subtype(p) do r:=link(r);
  17028. if best_ins_ptr(r)=null then wait:=true
  17029. else  begin wait:=false; s:=last_ins_ptr(r); link(s):=ins_ptr(p);
  17030.   if best_ins_ptr(r)=p then
  17031.     @<Wrap up the box specified by node |r|, splitting node |p| if
  17032.     called for; set |wait:=true| if node |p| holds a remainder after
  17033.     splitting@>
  17034.   else  begin while link(s)<>null do s:=link(s);
  17035.     last_ins_ptr(r):=s;
  17036.     end;
  17037.   end;
  17038. @<Either append the insertion node |p| after node |q|, and remove it
  17039.   from the current page, or delete |node(p)|@>;
  17040. @ @<Wrap up the box specified by node |r|, splitting node |p| if...@>=
  17041. begin if type(r)=split_up then
  17042.   if (broken_ins(r)=p)and(broken_ptr(r)<>null) then
  17043.     begin while link(s)<>broken_ptr(r) do s:=link(s);
  17044.     link(s):=null;
  17045.     split_top_skip:=split_top_ptr(p);
  17046.     ins_ptr(p):=prune_page_top(broken_ptr(r));
  17047.     if ins_ptr(p)<>null then
  17048.       begin temp_ptr:=vpack(ins_ptr(p),natural);
  17049.       height(p):=height(temp_ptr)+depth(temp_ptr);
  17050.       free_node(temp_ptr,box_node_size); wait:=true;
  17051.       end;
  17052.     end;
  17053. best_ins_ptr(r):=null;
  17054. n:=qo(subtype(r));
  17055. temp_ptr:=list_ptr(box(n));
  17056. free_node(box(n),box_node_size);
  17057. box(n):=vpack(temp_ptr,natural);
  17058. @ @<Either append the insertion node |p|...@>=
  17059. link(prev_p):=link(p); link(p):=null;
  17060. if wait then
  17061.   begin link(q):=p; q:=p; incr(insert_penalties);
  17062.   end
  17063. else  begin delete_glue_ref(split_top_ptr(p));
  17064.   free_node(p,ins_node_size);
  17065.   end;
  17066. p:=prev_p
  17067. @ The list of heldover insertions, running from |link(page_head)| to
  17068. |page_tail|, must be moved to the contribution list when the user has
  17069. specified no output routine.
  17070. @<Perform the default output routine@>=
  17071. begin if link(page_head)<>null then
  17072.   begin if link(contrib_head)=null then
  17073.     if nest_ptr=0 then tail:=page_tail@+else contrib_tail:=page_tail
  17074.   else link(page_tail):=link(contrib_head);
  17075.   link(contrib_head):=link(page_head);
  17076.   link(page_head):=null; page_tail:=page_head;
  17077.   end;
  17078. ship_out(box(255)); box(255):=null;
  17079. @ @<Explain that too many dead cycles have occurred in a row@>=
  17080. begin print_err("Output loop---"); print_int(dead_cycles);
  17081. @.Output loop...@>
  17082. print(" consecutive dead cycles");
  17083. help3("I've concluded that your \output is awry; it never does a")@/
  17084. ("\shipout, so I'm shipping \box255 out myself. Next time")@/
  17085. ("increase \maxdeadcycles if you want me to be more patient!"); error;
  17086. @ @<Fire up the user's output routine and |return|@>=
  17087. begin output_active:=true;
  17088. incr(dead_cycles);
  17089. push_nest; mode:=-vmode; prev_depth:=ignore_depth; mode_line:=-line;
  17090. begin_token_list(output_routine,output_text);
  17091. new_save_level(output_group); normal_paragraph;
  17092. scan_left_brace;
  17093. return;
  17094. @ When the user's output routine finishes, it has constructed a vlist
  17095. in internal vertical mode, and \TeX\ will do the following:
  17096. @<Resume the page builder after an output routine has come to an end@>=
  17097. begin if (loc<>null) or 
  17098.  ((token_type<>output_text)and(token_type<>backed_up)) then
  17099.   @<Recover from an unbalanced output routine@>;
  17100. end_token_list; {conserve stack space in case more outputs are triggered}
  17101. end_graf; unsave; output_active:=false; insert_penalties:=0;@/
  17102. @<Ensure that box 255 is empty after output@>;
  17103. if tail<>head then {current list goes after heldover insertions}
  17104.   begin link(page_tail):=link(head);
  17105.   page_tail:=tail;
  17106.   end;
  17107. if link(page_head)<>null then {and both go before heldover contributions}
  17108.   begin if link(contrib_head)=null then contrib_tail:=page_tail;
  17109.   link(page_tail):=link(contrib_head);
  17110.   link(contrib_head):=link(page_head);
  17111.   link(page_head):=null; page_tail:=page_head;
  17112.   end;
  17113. pop_nest; build_page;
  17114. @ @<Recover from an unbalanced output routine@>=
  17115. begin print_err("Unbalanced output routine");
  17116. @.Unbalanced output routine@>
  17117. help2("Your sneaky output routine has problematic {'s and/or }'s.")@/
  17118. ("I can't handle that very well; good luck."); error;
  17119. repeat get_token;
  17120. until loc=null;
  17121. end {loops forever if reading from a file, since |null=min_halfword<=0|}
  17122. @ @<Ensure that box 255 is empty after output@>=
  17123. if box(255)<>null then
  17124.   begin print_err("Output routine didn't use all of ");
  17125.   print_esc("box"); print_int(255);
  17126. @.Output routine didn't use...@>
  17127.   help3("Your \output commands should empty \box255,")@/
  17128.     ("e.g., by saying `\shipout\box255'.")@/
  17129.     ("Proceed; I'll discard its present contents.");
  17130.   box_error(255);
  17131.   end
  17132. @* \[46] The chief executive.
  17133. We come now to the |main_control| routine, which contains the master
  17134. switch that causes all the various pieces of \TeX\ to do their things,
  17135. in the right order.
  17136. In a sense, this is the grand climax of the program: It applies all the
  17137. tools that we have worked so hard to construct. In another sense, this is
  17138. the messiest part of the program: It necessarily refers to other pieces
  17139. of code all over the place, so that a person can't fully understand what is
  17140. going on without paging back and forth to be reminded of conventions that
  17141. are defined elsewhere. We are now at the hub of the web, the central nervous
  17142. system that touches most of the other parts and ties them together.
  17143. @^brain@>
  17144. The structure of |main_control| itself is quite simple. There's a label
  17145. called |big_switch|, at which point the next token of input is fetched
  17146. using |get_x_token|. Then the program branches at high speed into one of
  17147. about 100 possible directions, based on the value of the current
  17148. mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
  17149. indicates what to do next. For example, the case `|vmode+letter|' arises
  17150. when a letter occurs in vertical mode (or internal vertical mode); this
  17151. case leads to instructions that initialize a new paragraph and enter
  17152. horizontal mode.
  17153. The big |case| statement that contains this multiway switch has been labeled
  17154. |reswitch|, so that the program can |goto reswitch| when the next token
  17155. has already been fetched. Most of the cases are quite short; they call
  17156. an ``action procedure'' that does the work for that case, and then they
  17157. either |goto reswitch| or they ``fall through'' to the end of the |case|
  17158. statement, which returns control back to |big_switch|. Thus, |main_control|
  17159. is not an extremely large procedure, in spite of the multiplicity of things
  17160. it must do; it is small enough to be handled by \PASCAL\ compilers that put
  17161. severe restrictions on procedure size.
  17162. @!@^action procedure@>
  17163. One case is singled out for special treatment, because it accounts for most
  17164. of \TeX's activities in typical applications. The process of reading simple
  17165. text and converting it into |char_node| records, while looking for ligatures
  17166. and kerns, is part of \TeX's ``inner loop''; the whole program runs
  17167. efficiently when its inner loop is fast, so this part has been written
  17168. with particular care.
  17169. @ We shall concentrate first on the inner loop of |main_control|, deferring
  17170. consideration of the other cases until later.
  17171. @d big_switch=60 {go here to branch on the next token of input}
  17172. @d main_loop=70 {go here to typeset a string of consecutive characters}
  17173. @d main_loop_wrapup=80 {go here to finish a character or ligature}
  17174. @d main_loop_move=90 {go here to advance the ligature cursor}
  17175. @d main_loop_move_lig=95 {same, when advancing past a generated ligature}
  17176. @d main_loop_lookahead=100 {go here to bring in another character, if any}
  17177. @d main_lig_loop=110 {go here to check for ligatures or kerning}
  17178. @d append_normal_space=120 {go here to append a normal space between words}
  17179. @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
  17180. @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
  17181. procedure main_control; {governs \TeX's activities}
  17182. label big_switch,reswitch,main_loop,main_loop_wrapup,
  17183.   main_loop_move,main_loop_move+1,main_loop_move+2,main_loop_move_lig,
  17184.   main_loop_lookahead,main_loop_lookahead+1,
  17185.   main_lig_loop,main_lig_loop+1,main_lig_loop+2,
  17186.   append_normal_space,exit;
  17187. var@!t:integer; {general-purpose temporary variable}
  17188. begin if every_job<>null then begin_token_list(every_job,every_job_text);
  17189. big_switch: get_x_token;@/
  17190. reswitch: @<Give diagnostic information, if requested@>;
  17191. case abs(mode)+cur_cmd of
  17192. hmode+letter,hmode+other_char,hmode+char_given: goto main_loop;
  17193. hmode+char_num: begin scan_char_num; cur_chr:=cur_val; goto main_loop;@+end;
  17194. hmode+no_boundary: begin get_x_token;
  17195.   if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given)or
  17196.    (cur_cmd=char_num) then cancel_boundary:=true;
  17197.   goto reswitch;
  17198.   end;
  17199. hmode+spacer: if space_factor=1000 then goto append_normal_space
  17200.   else app_space;
  17201. hmode+ex_space,mmode+ex_space: goto append_normal_space;
  17202. @t\4@>@<Cases of |main_control| that are not part of the inner loop@>@;
  17203. end; {of the big |case| statement}
  17204. goto big_switch;
  17205. main_loop:@<Append character |cur_chr| and the following characters (if~any)
  17206.   to the current hlist in the current font; |goto reswitch| when
  17207.   a non-character has been fetched@>;
  17208. append_normal_space:@<Append a normal inter-word space to the current list,
  17209.   then |goto big_switch|@>;
  17210. exit:end;
  17211. @ When a new token has just been fetched at |big_switch|, we have an
  17212. ideal place to monitor \TeX's activity.
  17213. @^debugging@>
  17214. @<Give diagnostic information, if requested@>=
  17215. if interrupt<>0 then if OK_to_interrupt then
  17216.   begin back_input; check_interrupt; goto big_switch;
  17217.   end;
  17218. @!debug if panicking then check_mem(false);@+@;@+gubed
  17219. if tracing_commands>0 then show_cur_cmd_chr
  17220. @ The following part of the program was first written in a structured
  17221. manner, according to the philosophy that ``premature optimization is
  17222. the root of all evil.'' Then it was rearranged into pieces of
  17223. spaghetti so that the most common actions could proceed with little or
  17224. no redundancy.
  17225. The original unoptimized form of this algorithm resembles the
  17226. |reconstitute| procedure, which was described earlier in connection with
  17227. hyphenation. Again we have an implied ``cursor'' between characters
  17228. |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
  17229. contain a charnode as well as pseudo-ligatures; that stack is now
  17230. usually nonempty, because the next character of input (if any) has been
  17231. appended to it. In |main_control| we have
  17232. $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
  17233.   |font_bchar[cur_font]|,&otherwise;\cr}$$
  17234. except when |character(lig_stack)=font_false_bchar[cur_font]|.
  17235. Several additional global variables are needed.
  17236. @<Glob...@>=
  17237. @!main_f:internal_font_number; {the current font}
  17238. @!main_i:four_quarters; {character information bytes for |cur_l|}
  17239. @!main_j:four_quarters; {ligature/kern command}
  17240. @!main_k:font_index; {index into |font_info|}
  17241. @!main_p:pointer; {temporary register for list manipulation}
  17242. @!main_s:integer; {space factor value}
  17243. @!bchar:halfword; {right boundary character of current font, or |non_char|}
  17244. @!false_bchar:halfword; {nonexistent character matching |bchar|, or |non_char|}
  17245. @!cancel_boundary:boolean; {should the left boundary be ignored?}
  17246. @!ins_disc:boolean; {should we insert a discretionary node?}
  17247. @ The boolean variables of the main loop are normally false, and always reset
  17248. to false before the loop is left. That saves us the extra work of initializing
  17249. each time.
  17250. @<Set init...@>=
  17251. ligature_present:=false; cancel_boundary:=false; lft_hit:=false; rt_hit:=false;
  17252. ins_disc:=false;
  17253. @ We leave the |space_factor| unchanged if |sf_code(cur_chr)=0|; otherwise we
  17254. set it equal to |sf_code(cur_chr)|, except that it should never change
  17255. from a value less than 1000 to a value exceeding 1000. The most common
  17256. case is |sf_code(cur_chr)=1000|, so we want that case to be fast.
  17257. The overall structure of the main loop is presented here. Some program labels
  17258. are inside the individual sections.
  17259. @d adjust_space_factor==@t@>@;@/
  17260.   main_s:=sf_code(cur_chr);
  17261.   if main_s=1000 then space_factor:=1000
  17262.   else if main_s<1000 then
  17263.     begin if main_s>0 then space_factor:=main_s;
  17264.     end
  17265.   else if space_factor<1000 then space_factor:=1000
  17266.   else space_factor:=main_s
  17267. @<Append character |cur_chr|...@>=
  17268. adjust_space_factor;@/
  17269. main_f:=cur_font;
  17270. bchar:=font_bchar[main_f]; false_bchar:=font_false_bchar[main_f];
  17271. if mode>0 then if language<>clang then fix_language;
  17272. fast_get_avail(lig_stack); font(lig_stack):=main_f; cur_l:=qi(cur_chr);
  17273. character(lig_stack):=cur_l;@/
  17274. cur_q:=tail;
  17275. if cancel_boundary then
  17276.   begin cancel_boundary:=false; main_k:=non_address;
  17277.   end
  17278. else main_k:=bchar_label[main_f];
  17279. if main_k=non_address then goto main_loop_move+2; {no left boundary processing}
  17280. cur_r:=cur_l; cur_l:=non_char;
  17281. goto main_lig_loop+1; {begin with cursor after left boundary}
  17282. main_loop_wrapup:@<Make a ligature node, if |ligature_present|;
  17283.   insert a null discretionary, if appropriate@>;
  17284. main_loop_move:@<If the cursor is immediately followed by the right boundary,
  17285.   |goto reswitch|; if it's followed by an invalid character, |goto big_switch|;
  17286.   otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
  17287. main_loop_lookahead:@<Look ahead for another character, or leave |lig_stack|
  17288.   empty if there's none there@>;
  17289. main_lig_loop:@<If there's a ligature/kern command relevant to |cur_l| and
  17290.   |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
  17291. main_loop_move_lig:@<Move the cursor past a pseudo-ligature, then
  17292.   |goto main_loop_lookahead| or |main_lig_loop|@>
  17293. @ If the current horizontal list is empty, the reference to |character(tail)|
  17294. here is not strictly legal, since |tail| will be a node freshly returned by
  17295. |get_avail|. But this should cause no problem on most implementations, and we
  17296. do want the inner loop to be fast.
  17297. @^dirty Pascal@>
  17298. A discretionary break is not inserted for an explicit hyphen when we are in
  17299. restricted horizontal mode. In particular, this avoids putting discretionary
  17300. nodes inside of other discretionaries.
  17301. @d pack_lig(#)== {the parameter is either |rt_hit| or |false|}
  17302.   begin main_p:=new_ligature(main_f,cur_l,link(cur_q));
  17303.   if lft_hit then
  17304.     begin subtype(main_p):=2; lft_hit:=false;
  17305.     end;
  17306.   if # then if lig_stack=null then
  17307.     begin incr(subtype(main_p)); rt_hit:=false;
  17308.     end;
  17309.   link(cur_q):=main_p; tail:=main_p; ligature_present:=false;
  17310.   end
  17311. @d wrapup(#)==if cur_l<non_char then
  17312.   begin if character(tail)=qi(hyphen_char[main_f]) then if link(cur_q)>null then
  17313.     ins_disc:=true;
  17314.   if ligature_present then pack_lig(#);
  17315.   if ins_disc then
  17316.     begin ins_disc:=false;
  17317.     if mode>0 then tail_append(new_disc);
  17318.     end;
  17319.   end
  17320. @<Make a ligature node, if |ligature_present|;...@>=
  17321. wrapup(rt_hit)
  17322. @ @<If the cursor is immediately followed by the right boundary...@>=
  17323. if lig_stack=null then goto reswitch;
  17324. cur_q:=tail; cur_l:=character(lig_stack);
  17325. main_loop_move+1:if not is_char_node(lig_stack) then goto main_loop_move_lig;
  17326. main_loop_move+2:if(cur_chr<font_bc[main_f])or(cur_chr>font_ec[main_f]) then
  17327.   begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
  17328.   end;
  17329. main_i:=char_info(main_f)(cur_l);
  17330. if not char_exists(main_i) then
  17331.   begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
  17332.   end;
  17333. tail_append(lig_stack) {|main_loop_lookahead| is next}
  17334. @ Here we are at |main_loop_move_lig|.
  17335. When we begin this code we have |cur_q=tail| and |cur_l=character(lig_stack)|.
  17336. @<Move the cursor past a pseudo-ligature...@>=
  17337. main_p:=lig_ptr(lig_stack);
  17338. if main_p>null then tail_append(main_p);
  17339. temp_ptr:=lig_stack; lig_stack:=link(temp_ptr);
  17340. free_node(temp_ptr,small_node_size);
  17341. main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17342. if lig_stack=null then
  17343.   if main_p>null then goto main_loop_lookahead
  17344.   else cur_r:=bchar
  17345. else cur_r:=character(lig_stack);
  17346. goto main_lig_loop
  17347. @ The result of \.{\\char} can participate in a ligature or kern, so we must
  17348. look ahead for it.
  17349. @<Look ahead for another character...@>=
  17350. get_next; {set only |cur_cmd| and |cur_chr|, for speed}
  17351. if cur_cmd=letter then goto main_loop_lookahead+1;
  17352. if cur_cmd=other_char then goto main_loop_lookahead+1;
  17353. if cur_cmd=char_given then goto main_loop_lookahead+1;
  17354. x_token; {now expand and set |cur_cmd|, |cur_chr|, |cur_tok|}
  17355. if cur_cmd=letter then goto main_loop_lookahead+1;
  17356. if cur_cmd=other_char then goto main_loop_lookahead+1;
  17357. if cur_cmd=char_given then goto main_loop_lookahead+1;
  17358. if cur_cmd=char_num then
  17359.   begin scan_char_num; cur_chr:=cur_val; goto main_loop_lookahead+1;
  17360.   end;
  17361. if cur_cmd=no_boundary then bchar:=non_char;
  17362. cur_r:=bchar; lig_stack:=null; goto main_lig_loop;
  17363. main_loop_lookahead+1: adjust_space_factor;
  17364. fast_get_avail(lig_stack); font(lig_stack):=main_f;
  17365. cur_r:=qi(cur_chr); character(lig_stack):=cur_r;
  17366. if cur_r=false_bchar then cur_r:=non_char {this prevents spurious ligatures}
  17367. @ Even though comparatively few characters have a lig/kern program, several
  17368. of the instructions here count as part of \TeX's inner loop, since a
  17369. potentially long sequential search must be performed. For example, tests with
  17370. Computer Modern Roman showed that about 40 per cent of all characters
  17371. actually encountered in practice had a lig/kern program, and that about four
  17372. lig/kern commands were investigated for every such character.
  17373. At the beginning of this code we have |main_i=char_info(main_f)(cur_l)|.
  17374. @<If there's a ligature/kern command...@>=
  17375. if char_tag(main_i)<>lig_tag then goto main_loop_wrapup;
  17376. main_k:=lig_kern_start(main_f)(main_i); main_j:=font_info[main_k].qqqq;
  17377. if skip_byte(main_j)<=stop_flag then goto main_lig_loop+2;
  17378. main_k:=lig_kern_restart(main_f)(main_j);
  17379. main_lig_loop+1:main_j:=font_info[main_k].qqqq;
  17380. main_lig_loop+2:if next_char(main_j)=cur_r then
  17381.  if skip_byte(main_j)<=stop_flag then
  17382.   @<Do ligature or kern command, returning to |main_lig_loop|
  17383.   or |main_loop_wrapup| or |main_loop_move|@>;
  17384. if skip_byte(main_j)=qi(0) then incr(main_k)
  17385. else begin if skip_byte(main_j)>=stop_flag then goto main_loop_wrapup;
  17386.   main_k:=main_k+qo(skip_byte(main_j))+1;
  17387.   end;
  17388. goto main_lig_loop+1
  17389. @ When a ligature or kern instruction matches a character, we know from
  17390. |read_font_info| that the character exists in the font, even though we
  17391. haven't verified its existence in the normal way.
  17392. This section could be made into a subroutine, if the code inside
  17393. |main_control| needs to be shortened.
  17394. \chardef\?='174 % vertical line to indicate character retention
  17395. @<Do ligature or kern command...@>=
  17396. begin if op_byte(main_j)>=kern_flag then
  17397.   begin wrapup(rt_hit);
  17398.   tail_append(new_kern(char_kern(main_f)(main_j))); goto main_loop_move;
  17399.   end;
  17400. if cur_l=non_char then lft_hit:=true
  17401. else if lig_stack=null then rt_hit:=true;
  17402. check_interrupt; {allow a way out in case there's an infinite ligature loop}
  17403. case op_byte(main_j) of
  17404. qi(1),qi(5):begin cur_l:=rem_byte(main_j); {\.{=:\?}, \.{=:\?>}}
  17405.   main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17406.   end;
  17407. qi(2),qi(6):begin cur_r:=rem_byte(main_j); {\.{\?=:}, \.{\?=:>}}
  17408.   if lig_stack=null then {right boundary character is being consumed}
  17409.     begin lig_stack:=new_lig_item(cur_r); bchar:=non_char;
  17410.     end
  17411.   else if is_char_node(lig_stack) then {|link(lig_stack)=null|}
  17412.     begin main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
  17413.     lig_ptr(lig_stack):=main_p;
  17414.     end
  17415.   else character(lig_stack):=cur_r;
  17416.   end;
  17417. qi(3):begin cur_r:=rem_byte(main_j); {\.{\?=:\?}}
  17418.   main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
  17419.   link(lig_stack):=main_p;
  17420.   end;
  17421. qi(7),qi(11):begin wrapup(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
  17422.   cur_q:=tail; cur_l:=rem_byte(main_j);
  17423.   main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17424.   end;
  17425. othercases begin cur_l:=rem_byte(main_j); ligature_present:=true; {\.{=:}}
  17426.   if lig_stack=null then goto main_loop_wrapup
  17427.   else goto main_loop_move+1;
  17428.   end
  17429. endcases;
  17430. if op_byte(main_j)>qi(4) then
  17431.   if op_byte(main_j)<>qi(7) then goto main_loop_wrapup;
  17432. if cur_l<non_char then goto main_lig_loop;
  17433. main_k:=bchar_label[main_f]; goto main_lig_loop+1;
  17434. @ The occurrence of blank spaces is almost part of \TeX's inner loop,
  17435. since we usually encounter about one space for every five non-blank characters.
  17436. Therefore |main_control| gives second-highest priority to ordinary spaces.
  17437. When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
  17438. see to it later that the corresponding glue specification is precisely
  17439. |zero_glue|, not merely a pointer to some specification that happens
  17440. to be full of zeroes. Therefore it is simple to test whether a glue parameter
  17441. is zero or~not.
  17442. @<Append a normal inter-word space...@>=
  17443. if space_skip=zero_glue then
  17444.   begin @<Find the glue specification, |main_p|, for
  17445.     text spaces in the current font@>;
  17446.   temp_ptr:=new_glue(main_p);
  17447.   end
  17448. else temp_ptr:=new_param_glue(space_skip_code);
  17449. link(tail):=temp_ptr; tail:=temp_ptr;
  17450. goto big_switch
  17451. @ Having |font_glue| allocated for each text font saves both time and memory.
  17452. If any of the three spacing parameters are subsequently changed by the
  17453. use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
  17454. |font_glue| specification allocated here.
  17455. @<Find the glue specification...@>=
  17456. begin main_p:=font_glue[cur_font];
  17457. if main_p=null then
  17458.   begin main_p:=new_spec(zero_glue); main_k:=param_base[cur_font]+space_code;
  17459.   width(main_p):=font_info[main_k].sc; {that's |space(cur_font)|}
  17460.   stretch(main_p):=font_info[main_k+1].sc; {and |space_stretch(cur_font)|}
  17461.   shrink(main_p):=font_info[main_k+2].sc; {and |space_shrink(cur_font)|}
  17462.   font_glue[cur_font]:=main_p;
  17463.   end;
  17464. @ @<Declare act...@>=
  17465. procedure app_space; {handle spaces when |space_factor<>1000|}
  17466. var@!q:pointer; {glue node}
  17467. begin if (space_factor>=2000)and(xspace_skip<>zero_glue) then
  17468.   q:=new_param_glue(xspace_skip_code)
  17469. else  begin if space_skip<>zero_glue then main_p:=space_skip
  17470.   else @<Find the glue specification...@>;
  17471.   main_p:=new_spec(main_p);
  17472.   @<Modify the glue specification in |main_p| according to the space factor@>;
  17473.   q:=new_glue(main_p); glue_ref_count(main_p):=null;
  17474.   end;
  17475. link(tail):=q; tail:=q;
  17476. @ @<Modify the glue specification in |main_p| according to the space factor@>=
  17477. if space_factor>=2000 then width(main_p):=width(main_p)+extra_space(cur_font);
  17478. stretch(main_p):=xn_over_d(stretch(main_p),space_factor,1000);
  17479. shrink(main_p):=xn_over_d(shrink(main_p),1000,space_factor)
  17480. @ Whew---that covers the main loop. We can now proceed at a leisurely
  17481. pace through the other combinations of possibilities.
  17482. @d any_mode(#)==vmode+#,hmode+#,mmode+# {for mode-independent commands}
  17483. @<Cases of |main_control| that are not part of the inner loop@>=
  17484. any_mode(relax),vmode+spacer,mmode+spacer,mmode+no_boundary:do_nothing;
  17485. any_mode(ignore_spaces): begin @<Get the next non-blank non-call...@>;
  17486.   goto reswitch;
  17487.   end;
  17488. vmode+stop: if its_all_over then return; {this is the only way out}
  17489. @t\4@>@<Forbidden cases detected in |main_control|@>@+@,any_mode(mac_param):
  17490.   report_illegal_case;
  17491. @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign;
  17492. @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
  17493. @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
  17494. @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
  17495. @ Here is a list of cases where the user has probably gotten into or out of math
  17496. mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
  17497. @d non_math(#)==vmode+#,hmode+#
  17498. @<Math-only cases in non-math modes...@>=
  17499. non_math(sup_mark), non_math(sub_mark), non_math(math_char_num),
  17500. non_math(math_given), non_math(math_comp), non_math(delim_num),
  17501. non_math(left_right), non_math(above), non_math(radical),
  17502. non_math(math_style), non_math(math_choice), non_math(vcenter),
  17503. non_math(non_script), non_math(mkern), non_math(limit_switch),
  17504. non_math(mskip), non_math(math_accent),
  17505. mmode+endv, mmode+par_end, mmode+stop, mmode+vskip, mmode+un_vbox,
  17506. mmode+valign, mmode+hrule
  17507. @ @<Declare action...@>=
  17508. procedure insert_dollar_sign;
  17509. begin back_input; cur_tok:=math_shift_token+"$";
  17510. print_err("Missing $ inserted");
  17511. @.Missing \$ inserted@>
  17512. help2("I've inserted a begin-math/end-math symbol since I think")@/
  17513. ("you left one out. Proceed, with fingers crossed."); ins_error;
  17514. @ When erroneous situations arise, \TeX\ usually issues an error message
  17515. specific to the particular error. For example, `\.{\\noalign}' should
  17516. not appear in any mode, since it is recognized by the |align_peek| routine
  17517. in all of its legitimate appearances; a special error message is given
  17518. when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
  17519. error message is simply that the user is not allowed to do what he or she
  17520. has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
  17521. and `\.{\\lower}' only in non-vertical modes.  Such cases are enumerated
  17522. here and in the other sections referred to under `See also \dots.'
  17523. @<Forbidden cases...@>=
  17524. vmode+vmove,hmode+hmove,mmode+hmove,any_mode(last_item),
  17525. @ The `|you_cant|' procedure prints a line saying that the current command
  17526. is illegal in the current mode; it identifies these things symbolically.
  17527. @<Declare action...@>=
  17528. procedure you_cant;
  17529. begin print_err("You can't use `");
  17530. @.You can't use x in y mode@>
  17531. print_cmd_chr(cur_cmd,cur_chr);
  17532. print("' in "); print_mode(mode);
  17533. @ @<Declare act...@>=
  17534. procedure report_illegal_case;
  17535. begin you_cant;
  17536. help4("Sorry, but I'm not programmed to handle this case;")@/
  17537. ("I'll just pretend that you didn't ask for it.")@/
  17538. ("If you're in the wrong mode, you might be able to")@/
  17539. ("return to the right one by typing `I}' or `I$' or `I\par'.");@/
  17540. error;
  17541. @ Some operations are allowed only in privileged modes, i.e., in cases
  17542. that |mode>0|. The |privileged| function is used to detect violations
  17543. of this rule; it issues an error message and returns |false| if the
  17544. current |mode| is negative.
  17545. @<Declare act...@>=
  17546. function privileged:boolean;
  17547. begin if mode>0 then privileged:=true
  17548. else  begin report_illegal_case; privileged:=false;
  17549.   end;
  17550. @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
  17551. endgame, since both of them have `|stop|' as their command code.
  17552. @<Put each...@>=
  17553. primitive("end",stop,0);@/
  17554. @!@:end_}{\.{\\end} primitive@>
  17555. primitive("dump",stop,1);@/
  17556. @!@:dump_}{\.{\\dump} primitive@>
  17557. @ @<Cases of |print_cmd_chr|...@>=
  17558. stop:if chr_code=1 then print_esc("dump")@+else print_esc("end");
  17559. @ We don't want to leave |main_control| immediately when a |stop| command
  17560. is sensed, because it may be necessary to invoke an \.{\\output} routine
  17561. several times before things really grind to a halt. (The output routine
  17562. might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
  17563. Therefore |its_all_over| is |true| only when the current page
  17564. and contribution list are empty, and when the last output was not a
  17565. ``dead cycle.''
  17566. @<Declare act...@>=
  17567. function its_all_over:boolean; {do this when \.{\\end} or \.{\\dump} occurs}
  17568. label exit;
  17569. begin if privileged then
  17570.   begin if (page_head=page_tail)and(head=tail)and(dead_cycles=0) then
  17571.     begin its_all_over:=true; return;
  17572.     end;
  17573.   back_input; {we will try to end again after ejecting residual material}
  17574.   tail_append(new_null_box);
  17575.   width(tail):=hsize;
  17576.   tail_append(new_glue(fill_glue));
  17577.   tail_append(new_penalty(-@'10000000000));@/
  17578.   build_page; {append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}}
  17579.   end;
  17580. its_all_over:=false;
  17581. exit:end;
  17582. @* \[47] Building boxes and lists.
  17583. The most important parts of |main_control| are concerned with \TeX's
  17584. chief mission of box-making. We need to control the activities that put
  17585. entries on vlists and hlists, as well as the activities that convert
  17586. those lists into boxes. All of the necessary machinery has already been
  17587. developed; it remains for us to ``push the buttons'' at the right times.
  17588. @ As an introduction to these routines, let's consider one of the simplest
  17589. cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
  17590. `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
  17591. is short, since the |scan_rule_spec| routine already does most of what is
  17592. required; thus, there is no need for a special action procedure.
  17593. Note that baselineskip calculations are disabled after a rule in vertical
  17594. mode, by setting |prev_depth:=ignore_depth|.
  17595. @<Cases of |main_control| that build...@>=
  17596. vmode+hrule,hmode+vrule,mmode+vrule: begin tail_append(scan_rule_spec);
  17597.   if abs(mode)=vmode then prev_depth:=ignore_depth
  17598.   else if abs(mode)=hmode then space_factor:=1000;
  17599.   end;
  17600. @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
  17601. more complicated. But the code in |main_control| is very short, since
  17602. it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
  17603. activates |append_kern|.
  17604. @<Cases of |main_control| that build...@>=
  17605. vmode+vskip,hmode+hskip,mmode+hskip,mmode+mskip: append_glue;
  17606. any_mode(kern),mmode+mkern: append_kern;
  17607. @ The |hskip| and |vskip| command codes are used for control sequences
  17608. like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
  17609. The difference is in the value of |cur_chr|.
  17610. @d fil_code=0 {identifies \.{\\hfil} and \.{\\vfil}}
  17611. @d fill_code=1 {identifies \.{\\hfill} and \.{\\vfill}}
  17612. @d ss_code=2 {identifies \.{\\hss} and \.{\\vss}}
  17613. @d fil_neg_code=3 {identifies \.{\\hfilneg} and \.{\\vfilneg}}
  17614. @d skip_code=4 {identifies \.{\\hskip} and \.{\\vskip}}
  17615. @d mskip_code=5 {identifies \.{\\mskip}}
  17616. @<Put each...@>=
  17617. primitive("hskip",hskip,skip_code);@/
  17618. @!@:hskip_}{\.{\\hskip} primitive@>
  17619. primitive("hfil",hskip,fil_code);
  17620. @!@:hfil_}{\.{\\hfil} primitive@>
  17621. primitive("hfill",hskip,fill_code);@/
  17622. @!@:hfill_}{\.{\\hfill} primitive@>
  17623. primitive("hss",hskip,ss_code);
  17624. @!@:hss_}{\.{\\hss} primitive@>
  17625. primitive("hfilneg",hskip,fil_neg_code);@/
  17626. @!@:hfil_neg_}{\.{\\hfilneg} primitive@>
  17627. primitive("vskip",vskip,skip_code);@/
  17628. @!@:vskip_}{\.{\\vskip} primitive@>
  17629. primitive("vfil",vskip,fil_code);
  17630. @!@:vfil_}{\.{\\vfil} primitive@>
  17631. primitive("vfill",vskip,fill_code);@/
  17632. @!@:vfill_}{\.{\\vfill} primitive@>
  17633. primitive("vss",vskip,ss_code);
  17634. @!@:vss_}{\.{\\vss} primitive@>
  17635. primitive("vfilneg",vskip,fil_neg_code);@/
  17636. @!@:vfil_neg_}{\.{\\vfilneg} primitive@>
  17637. primitive("mskip",mskip,mskip_code);@/
  17638. @!@:mskip_}{\.{\\mskip} primitive@>
  17639. primitive("kern",kern,explicit);
  17640. @!@:kern_}{\.{\\kern} primitive@>
  17641. primitive("mkern",mkern,mu_glue);@/
  17642. @!@:mkern_}{\.{\\mkern} primitive@>
  17643. @ @<Cases of |print_cmd_chr|...@>=
  17644. hskip: case chr_code of
  17645.   skip_code:print_esc("hskip");
  17646.   fil_code:print_esc("hfil");
  17647.   fill_code:print_esc("hfill");
  17648.   ss_code:print_esc("hss");
  17649.   othercases print_esc("hfilneg")
  17650.   endcases;
  17651. vskip: case chr_code of
  17652.   skip_code:print_esc("vskip");
  17653.   fil_code:print_esc("vfil");
  17654.   fill_code:print_esc("vfill");
  17655.   ss_code:print_esc("vss");
  17656.   othercases print_esc("vfilneg")
  17657.   endcases;
  17658. mskip: print_esc("mskip");
  17659. kern: print_esc("kern");
  17660. mkern: print_esc("mkern");
  17661. @ All the work relating to glue creation has been relegated to the
  17662. following subroutine. It does not call |build_page|, because it is
  17663. used in at least one place where that would be a mistake.
  17664. @<Declare action...@>=
  17665. procedure append_glue;
  17666. var s:small_number; {modifier of skip command}
  17667. begin s:=cur_chr;
  17668. case s of
  17669. fil_code: cur_val:=fil_glue;
  17670. fill_code: cur_val:=fill_glue;
  17671. ss_code: cur_val:=ss_glue;
  17672. fil_neg_code: cur_val:=fil_neg_glue;
  17673. skip_code: scan_glue(glue_val);
  17674. mskip_code: scan_glue(mu_val);
  17675. end; {now |cur_val| points to the glue specification}
  17676. tail_append(new_glue(cur_val));
  17677. if s>=skip_code then
  17678.   begin decr(glue_ref_count(cur_val));
  17679.   if s>skip_code then subtype(tail):=mu_glue;
  17680.   end;
  17681. @ @<Declare act...@>=
  17682. procedure append_kern;
  17683. var s:quarterword; {|subtype| of the kern node}
  17684. begin s:=cur_chr; scan_dimen(s=mu_glue,false,false);
  17685. tail_append(new_kern(cur_val)); subtype(tail):=s;
  17686. @ Many of the actions related to box-making are triggered by the appearance
  17687. of braces in the input. For example, when the user says `\.{\\hbox}
  17688. \.{to} \.{100pt\{$\langle\,\hbox{hlist}\,\rangle$\}}' in vertical mode,
  17689. the information about the box size (100pt, |exactly|) is put onto |save_stack|
  17690. with a level boundary word just above it, and |cur_group:=adjusted_hbox_group|;
  17691. \TeX\ enters restricted horizontal mode to process the hlist. The right
  17692. brace eventually causes |save_stack| to be restored to its former state,
  17693. at which time the information about the box size (100pt, |exactly|) is
  17694. available once again; a box is packaged and we leave restricted horizontal
  17695. mode, appending the new box to the current list of the enclosing mode
  17696. (in this case to the current list of vertical mode), followed by any
  17697. vertical adjustments that were removed from the box by |hpack|.
  17698. The next few sections of the program are therefore concerned with the
  17699. treatment of left and right curly braces.
  17700. @ If a left brace occurs in the middle of a page or paragraph, it simply
  17701. introduces a new level of grouping, and the matching right brace will not have
  17702. such a drastic effect. Such grouping affects neither the mode nor the
  17703. current list.
  17704. @<Cases of |main_control| that build...@>=
  17705. non_math(left_brace): new_save_level(simple_group);
  17706. any_mode(begin_group): new_save_level(semi_simple_group);
  17707. any_mode(end_group): if cur_group=semi_simple_group then unsave
  17708.   else off_save;
  17709. @ We have to deal with errors in which braces and such things are not
  17710. properly nested. Sometimes the user makes an error of commission by
  17711. inserting an extra symbol, but sometimes the user makes an error of omission.
  17712. \TeX\ can't always tell one from the other, so it makes a guess and tries
  17713. to avoid getting into a loop.
  17714. The |off_save| routine is called when the current group code is wrong. It tries
  17715. to insert something into the user's input that will help clean off
  17716. the top level.
  17717. @<Declare act...@>=
  17718. procedure off_save;
  17719. var p:pointer; {inserted token}
  17720. begin if cur_group=bottom_level then
  17721.   @<Drop current token and complain that it was unmatched@>
  17722. else  begin back_input; p:=get_avail; link(temp_head):=p;
  17723.   print_err("Missing ");
  17724.   @<Prepare to insert a token that matches |cur_group|,
  17725.     and print what it is@>;
  17726.   print(" inserted"); ins_list(link(temp_head));
  17727.   help5("I've inserted something that you may have forgotten.")@/
  17728.   ("(See the <inserted text> above.)")@/
  17729.   ("With luck, this will get me unwedged. But if you")@/
  17730.   ("really didn't forget anything, try typing `2' now; then")@/
  17731.   ("my insertion and my current dilemma will both disappear.");
  17732.   error;
  17733.   end;
  17734. @ At this point, |link(temp_head)=p|, a pointer to an empty one-word node.
  17735. @<Prepare to insert a token that matches |cur_group|...@>=
  17736. case cur_group of
  17737. semi_simple_group: begin info(p):=cs_token_flag+frozen_end_group;
  17738.   print_esc("endgroup");
  17739. @.Missing \\endgroup inserted@>
  17740.   end;
  17741. math_shift_group: begin info(p):=math_shift_token+"$"; print_char("$");
  17742. @.Missing \$ inserted@>
  17743.   end;
  17744. math_left_group: begin info(p):=cs_token_flag+frozen_right; link(p):=get_avail;
  17745.   p:=link(p); info(p):=other_token+"."; print_esc("right.");
  17746. @.Missing \\right\hbox{.} inserted@>
  17747. @^null delimiter@>
  17748.   end;
  17749. othercases begin info(p):=right_brace_token+"}"; print_char("}");
  17750. @.Missing \} inserted@>
  17751.   end
  17752. endcases
  17753. @ @<Drop current token and complain that it was unmatched@>=
  17754. begin print_err("Extra "); print_cmd_chr(cur_cmd,cur_chr);
  17755. @.Extra x@>
  17756. help1("Things are pretty mixed up, but I think the worst is over.");@/
  17757. error;
  17758. @ The routine for a |right_brace| character branches into many subcases,
  17759. since a variety of things may happen, depending on |cur_group|. Some
  17760. types of groups are not supposed to be ended by a right brace; error
  17761. messages are given in hopes of pinpointing the problem. Most branches
  17762. of this routine will be filled in later, when we are ready to understand
  17763. them; meanwhile, we must prepare ourselves to deal with such errors.
  17764. @<Cases of |main_control| that build...@>=
  17765. any_mode(right_brace): handle_right_brace;
  17766. @ @<Declare the procedure called |handle_right_brace|@>=
  17767. procedure handle_right_brace;
  17768. var p,@!q:pointer; {for short-term use}
  17769. @!d:scaled; {holds |split_max_depth| in |insert_group|}
  17770. @!f:integer; {holds |floating_penalty| in |insert_group|}
  17771. begin case cur_group of
  17772. simple_group: unsave;
  17773. bottom_level: begin print_err("Too many }'s");
  17774. @.Too many \}'s@>
  17775.   help2("You've closed more groups than you opened.")@/
  17776.   ("Such booboos are generally harmless, so keep going."); error;
  17777.   end;
  17778. semi_simple_group,math_shift_group,math_left_group: extra_right_brace;
  17779. @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers
  17780.   a delayed action@>@;
  17781. othercases confusion("rightbrace")
  17782. @:this can't happen rightbrace}{\quad rightbrace@>
  17783. endcases;
  17784. @ @<Declare act...@>=
  17785. procedure extra_right_brace;
  17786. begin print_err("Extra }, or forgotten ");
  17787. @.Extra \}, or forgotten x@>
  17788. case cur_group of
  17789. semi_simple_group: print_esc("endgroup");
  17790. math_shift_group: print_char("$");
  17791. math_left_group: print_esc("right");
  17792. end;@/
  17793. help5("I've deleted a group-closing symbol because it seems to be")@/
  17794. ("spurious, as in `$x}$'. But perhaps the } is legitimate and")@/
  17795. ("you forgot something else, as in `\hbox{$x}'. In such cases")@/
  17796. ("the way to recover is to insert both the forgotten and the")@/
  17797. ("deleted material, e.g., by typing `I$}'."); error;
  17798. incr(align_state);
  17799. @ Here is where we clear the parameters that are supposed to revert to their
  17800. default values after every paragraph and when internal vertical mode is entered.
  17801. @<Declare act...@>=
  17802. procedure normal_paragraph;
  17803. begin if looseness<>0 then eq_word_define(int_base+looseness_code,0);
  17804. if hang_indent<>0 then eq_word_define(dimen_base+hang_indent_code,0);
  17805. if hang_after<>1 then eq_word_define(int_base+hang_after_code,1);
  17806. if par_shape_ptr<>null then eq_define(par_shape_loc,shape_ref,null);
  17807. @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
  17808. need to consider also a slightly larger context, since constructions like
  17809. `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
  17810. `\.{\\leaders}\penalty0\.{\\hbox...}' and
  17811. `\.{\\lower3.8pt\\hbox...}'
  17812. are supposed to invoke quite
  17813. different actions after the box has been packaged. Conversely,
  17814. constructions like `\.{\\setbox3=}' can be followed by a variety of
  17815. different kinds of boxes, and we would like to encode such things in an
  17816. efficient way.
  17817. In other words, there are two problems: To represent the context of a box,
  17818. and to represent its type.
  17819. The first problem is solved by putting a ``context code'' on the |save_stack|,
  17820. just below the two entries that give the dimensions produced by |scan_spec|.
  17821. The context code is either a (signed) shift amount, or it is a large
  17822. integer |>=box_flag|, where |box_flag=@t$2^{30}$@>|. Codes |box_flag| through
  17823. |box_flag+255| represent `\.{\\setbox0}' through `\.{\\setbox255}';
  17824. codes |box_flag+256| through |box_flag+511| represent `\.{\\global\\setbox0}'
  17825. through `\.{\\global\\setbox255}';
  17826. code |box_flag+512| represents `\.{\\shipout}'; and codes |box_flag+513|
  17827. through |box_flag+515| represent `\.{\\leaders}', `\.{\\cleaders}',
  17828. and `\.{\\xleaders}'.
  17829. The second problem is solved by giving the command code |make_box| to all
  17830. control sequences that produce a box, and by using the following |chr_code|
  17831. values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
  17832. |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|,
  17833. where the latter two are used denote \.{\\vbox} and \.{\\hbox}, respectively.
  17834. @d box_flag==@'10000000000 {context code for `\.{\\setbox0}'}
  17835. @d ship_out_flag==box_flag+512 {context code for `\.{\\shipout}'}
  17836. @d leader_flag==box_flag+513 {context code for `\.{\\leaders}'}
  17837. @d box_code=0 {|chr_code| for `\.{\\box}'}
  17838. @d copy_code=1 {|chr_code| for `\.{\\copy}'}
  17839. @d last_box_code=2 {|chr_code| for `\.{\\lastbox}'}
  17840. @d vsplit_code=3 {|chr_code| for `\.{\\vsplit}'}
  17841. @d vtop_code=4 {|chr_code| for `\.{\\vtop}'}
  17842. @<Put each...@>=
  17843. primitive("moveleft",hmove,1);
  17844. @!@:move_left_}{\.{\\moveleft} primitive@>
  17845. primitive("moveright",hmove,0);@/
  17846. @!@:move_right_}{\.{\\moveright} primitive@>
  17847. primitive("raise",vmove,1);
  17848. @!@:raise_}{\.{\\raise} primitive@>
  17849. primitive("lower",vmove,0);
  17850. @!@:lower_}{\.{\\lower} primitive@>
  17851. primitive("box",make_box,box_code);
  17852. @!@:box_}{\.{\\box} primitive@>
  17853. primitive("copy",make_box,copy_code);
  17854. @!@:copy_}{\.{\\copy} primitive@>
  17855. primitive("lastbox",make_box,last_box_code);
  17856. @!@:last_box_}{\.{\\lastbox} primitive@>
  17857. primitive("vsplit",make_box,vsplit_code);
  17858. @!@:vsplit_}{\.{\\vsplit} primitive@>
  17859. primitive("vtop",make_box,vtop_code);@/
  17860. @!@:vtop_}{\.{\\vtop} primitive@>
  17861. primitive("vbox",make_box,vtop_code+vmode);
  17862. @!@:vbox_}{\.{\\vbox} primitive@>
  17863. primitive("hbox",make_box,vtop_code+hmode);@/
  17864. @!@:hbox_}{\.{\\hbox} primitive@>
  17865. primitive("shipout",leader_ship,a_leaders-1); {|ship_out_flag=leader_flag-1|}
  17866. @!@:ship_out_}{\.{\\shipout} primitive@>
  17867. primitive("leaders",leader_ship,a_leaders);
  17868. @!@:leaders_}{\.{\\leaders} primitive@>
  17869. primitive("cleaders",leader_ship,c_leaders);
  17870. @!@:c_leaders_}{\.{\\cleaders} primitive@>
  17871. primitive("xleaders",leader_ship,x_leaders);
  17872. @!@:x_leaders_}{\.{\\xleaders} primitive@>
  17873. @ @<Cases of |print_cmd_chr|...@>=
  17874. hmove: if chr_code=1 then print_esc("moveleft")@+else print_esc("moveright");
  17875. vmove: if chr_code=1 then print_esc("raise")@+else print_esc("lower");
  17876. make_box: case chr_code of
  17877.   box_code: print_esc("box");
  17878.   copy_code: print_esc("copy");
  17879.   last_box_code: print_esc("lastbox");
  17880.   vsplit_code: print_esc("vsplit");
  17881.   vtop_code: print_esc("vtop");
  17882.   vtop_code+vmode: print_esc("vbox");
  17883.   othercases print_esc("hbox")
  17884.   endcases;
  17885. leader_ship: if chr_code=a_leaders then print_esc("leaders")
  17886.   else if chr_code=c_leaders then print_esc("cleaders")
  17887.   else if chr_code=x_leaders then print_esc("xleaders")
  17888.   else print_esc("shipout");
  17889. @ Constructions that require a box are started by calling |scan_box| with
  17890. a specified context code. The |scan_box| routine verifies
  17891. that a |make_box| command comes next and then it calls |begin_box|.
  17892. @<Cases of |main_control| that build...@>=
  17893. vmode+hmove,hmode+vmove,mmode+vmove: begin t:=cur_chr;
  17894.   scan_normal_dimen;
  17895.   if t=0 then scan_box(cur_val)@+else scan_box(-cur_val);
  17896.   end;
  17897. any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);
  17898. any_mode(make_box): begin_box(0);
  17899. @ The global variable |cur_box| will point to a newly-made box. If the box
  17900. is void, we will have |cur_box=null|. Otherwise we will have
  17901. |type(cur_box)=hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
  17902. case can occur only with leaders.
  17903. @<Glob...@>=
  17904. @!cur_box:pointer; {box to be placed into its context}
  17905. @ The |box_end| procedure does the right thing with |cur_box|, if
  17906. |box_context| represents the context as explained above.
  17907. @<Declare act...@>=
  17908. procedure box_end(@!box_context:integer);
  17909. var p:pointer; {|ord_noad| for new box in math mode}
  17910. begin if box_context<box_flag then @<Append box |cur_box| to the current list,
  17911.     shifted by |box_context|@>
  17912. else if box_context<ship_out_flag then @<Store \(c)|cur_box| in a box register@>
  17913. else if cur_box<>null then
  17914.   if box_context>ship_out_flag then @<Append a new leader node that
  17915.       uses |cur_box|@>
  17916.   else ship_out(cur_box);
  17917. @ The global variable |adjust_tail| will be non-null if and only if the
  17918. current box might include adjustments that should be appended to the
  17919. current vertical list.
  17920. @<Append box |cur_box| to the current...@>=
  17921. begin if cur_box<>null then
  17922.   begin shift_amount(cur_box):=box_context;
  17923.   if abs(mode)=vmode then
  17924.     begin append_to_vlist(cur_box);
  17925.     if adjust_tail<>null then
  17926.       begin if adjust_head<>adjust_tail then
  17927.         begin link(tail):=link(adjust_head); tail:=adjust_tail;
  17928.         end;
  17929.       adjust_tail:=null;
  17930.       end;
  17931.     if mode>0 then build_page;
  17932.     end
  17933.   else  begin if abs(mode)=hmode then space_factor:=1000
  17934.     else  begin p:=new_noad;
  17935.       math_type(nucleus(p)):=sub_box;
  17936.       info(nucleus(p)):=cur_box; cur_box:=p;
  17937.       end;
  17938.     link(tail):=cur_box; tail:=cur_box;
  17939.     end;
  17940.   end;
  17941. @ @<Store \(c)|cur_box| in a box register@>=
  17942. if box_context<box_flag+256 then
  17943.   eq_define(box_base-box_flag+box_context,box_ref,cur_box)
  17944. else geq_define(box_base-box_flag-256+box_context,box_ref,cur_box)
  17945. @ @<Append a new leader node ...@>=
  17946. begin @<Get the next non-blank non-relax...@>;
  17947. if ((cur_cmd=hskip)and(abs(mode)<>vmode))or@|
  17948.    ((cur_cmd=vskip)and(abs(mode)=vmode))or@|
  17949.    ((cur_cmd=mskip)and(abs(mode)=mmode)) then
  17950.   begin append_glue; subtype(tail):=box_context-(leader_flag-a_leaders);
  17951.   leader_ptr(tail):=cur_box;
  17952.   end
  17953. else  begin print_err("Leaders not followed by proper glue");
  17954. @.Leaders not followed by...@>
  17955.   help3("You should say `\leaders <box or rule><hskip or vskip>'.")@/
  17956.   ("I found the <box or rule>, but there's no suitable")@/
  17957.   ("<hskip or vskip>, so I'm ignoring these leaders."); back_error;
  17958.   flush_node_list(cur_box);
  17959.   end;
  17960. @ Now that we can see what eventually happens to boxes, we can consider
  17961. the first steps in their creation. The |begin_box| routine is called when
  17962. |box_context| is a context specification, |cur_chr| specifies the type of
  17963. box desired, and |cur_cmd=make_box|.
  17964. @<Declare act...@>=
  17965. procedure begin_box(@!box_context:integer);
  17966. label exit, done;
  17967. var @!p,@!q:pointer; {run through the current list}
  17968. @!m:quarterword; {the length of a replacement list}
  17969. @!k:halfword; {0 or |vmode| or |hmode|}
  17970. @!n:eight_bits; {a box number}
  17971. begin case cur_chr of
  17972. box_code: begin scan_eight_bit_int; cur_box:=box(cur_val);
  17973.   box(cur_val):=null; {the box becomes void, at the same level}
  17974.   end;
  17975. copy_code: begin scan_eight_bit_int; cur_box:=copy_node_list(box(cur_val));
  17976.   end;
  17977. last_box_code: @<If the current list ends with a box node, delete it from
  17978.   the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>;
  17979. vsplit_code: @<Split off part of a vertical box, make |cur_box| point to it@>;
  17980. othercases @<Initiate the construction of an hbox or vbox, then |return|@>
  17981. endcases;@/
  17982. box_end(box_context); {in simple cases, we use the box immediately}
  17983. exit:end;
  17984. @ Note that the condition |not is_char_node(tail)| implies that |head<>tail|,
  17985. since |head| is a one-word node.
  17986. @<If the current list ends with a box node, delete it...@>=
  17987. begin cur_box:=null;
  17988. if abs(mode)=mmode then
  17989.   begin you_cant; help1("Sorry; this \lastbox will be void."); error;
  17990.   end
  17991. else if (mode=vmode)and(head=tail) then
  17992.   begin you_cant;
  17993.   help2("Sorry...I usually can't take things from the current page.")@/
  17994.     ("This \lastbox will therefore be void."); error;
  17995.   end
  17996. else  begin if not is_char_node(tail) then
  17997.     if (type(tail)=hlist_node)or(type(tail)=vlist_node) then
  17998.       @<Remove the last box, unless it's part of a discretionary@>;
  17999.   end;
  18000. @ @<Remove the last box...@>=
  18001. begin q:=head;
  18002. repeat p:=q;
  18003. if not is_char_node(q) then if type(q)=disc_node then
  18004.   begin for m:=1 to replace_count(q) do p:=link(p);
  18005.   if p=tail then goto done;
  18006.   end;
  18007. q:=link(p);
  18008. until q=tail;
  18009. cur_box:=tail; shift_amount(cur_box):=0;
  18010. tail:=p; link(p):=null;
  18011. done:end
  18012. @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
  18013. @<Split off part of a vertical box, make |cur_box| point to it@>=
  18014. begin scan_eight_bit_int; n:=cur_val;
  18015. if not scan_keyword("to") then
  18016. @.to@>
  18017.   begin print_err("Missing `to' inserted");
  18018. @.Missing `to' inserted@>
  18019.   help2("I'm working on `\vsplit<box number> to <dimen>';")@/
  18020.   ("will look for the <dimen> next."); error;
  18021.   end;
  18022. scan_normal_dimen;
  18023. cur_box:=vsplit(n,cur_val);
  18024. @ Here is where we enter restricted horizontal mode or internal vertical
  18025. mode, in order to make a box.
  18026. @<Initiate the construction of an hbox or vbox, then |return|@>=
  18027. begin k:=cur_chr-vtop_code; saved(0):=box_context;
  18028. if k=hmode then
  18029.   if (box_context<box_flag)and(abs(mode)=vmode) then
  18030.     scan_spec(adjusted_hbox_group,true)
  18031.   else scan_spec(hbox_group,true)
  18032. else  begin if k=vmode then scan_spec(vbox_group,true)
  18033.   else  begin scan_spec(vtop_group,true); k:=vmode;
  18034.     end;
  18035.   normal_paragraph;
  18036.   end;
  18037. push_nest; mode:=-k;
  18038. if k=vmode then
  18039.   begin prev_depth:=ignore_depth;
  18040.   if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
  18041.   end
  18042. else  begin space_factor:=1000;
  18043.   if every_hbox<>null then begin_token_list(every_hbox,every_hbox_text);
  18044.   end;
  18045. return;
  18046. @ @<Declare act...@>=
  18047. procedure scan_box(@!box_context:integer);
  18048.   {the next input should specify a box or perhaps a rule}
  18049. begin @<Get the next non-blank non-relax...@>;
  18050. if cur_cmd=make_box then begin_box(box_context)
  18051. else if (box_context>=leader_flag)and((cur_cmd=hrule)or(cur_cmd=vrule)) then
  18052.   begin cur_box:=scan_rule_spec; box_end(box_context);
  18053.   end
  18054. else  begin@t@>@;@/
  18055.   print_err("A <box> was supposed to be here");@/
  18056. @.A <box> was supposed to...@>
  18057.   help3("I was expecting to see \hbox or \vbox or \copy or \box or")@/
  18058.   ("something like that. So you might find something missing in")@/
  18059.   ("your output. But keep trying; you can fix this later."); back_error;
  18060.   end;
  18061. @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
  18062. \.{\\vtop} construction, the |package| routine comes into action. We might
  18063. also have to finish a paragraph that hasn't ended.
  18064. @<Cases of |handle...@>=
  18065. hbox_group: package(0);
  18066. adjusted_hbox_group: begin adjust_tail:=adjust_head; package(0);
  18067.   end;
  18068. vbox_group: begin end_graf; package(0);
  18069.   end;
  18070. vtop_group: begin end_graf; package(vtop_code);
  18071.   end;
  18072. @ @<Declare action...@>=
  18073. procedure package(@!c:small_number);
  18074. var h:scaled; {height of box}
  18075. @!p:pointer; {first node in a box}
  18076. @!d:scaled; {max depth}
  18077. begin d:=box_max_depth; unsave; save_ptr:=save_ptr-3;
  18078. if mode=-hmode then cur_box:=hpack(link(head),saved(2),saved(1))
  18079. else  begin cur_box:=vpackage(link(head),saved(2),saved(1),d);
  18080.   if c=vtop_code then @<Readjust the height and depth of |cur_box|,
  18081.     for \.{\\vtop}@>;
  18082.   end;
  18083. pop_nest; box_end(saved(0));
  18084. @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
  18085. if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
  18086. the \.{\\vtop} height is zero.
  18087. @<Readjust the height...@>=
  18088. begin h:=0; p:=list_ptr(cur_box);
  18089. if p<>null then if type(p)<=rule_node then h:=height(p);
  18090. depth(cur_box):=depth(cur_box)-h+height(cur_box); height(cur_box):=h;
  18091. @ A paragraph begins when horizontal-mode material occurs in vertical mode,
  18092. or when the paragraph is explicitly started by `\.{\\indent}' or
  18093. `\.{\\noindent}'.
  18094. @<Put each...@>=
  18095. primitive("indent",start_par,1);
  18096. @!@:indent_}{\.{\\indent} primitive@>
  18097. primitive("noindent",start_par,0);
  18098. @!@:no_indent_}{\.{\\noindent} primitive@>
  18099. @ @<Cases of |print_cmd_chr|...@>=
  18100. start_par: if chr_code=0 then print_esc("noindent")@+ else print_esc("indent");
  18101. @ @<Cases of |main_control| that build...@>=
  18102. vmode+start_par: new_graf(cur_chr>0);
  18103. vmode+letter,vmode+other_char,vmode+char_num,vmode+char_given,
  18104.    vmode+math_shift,vmode+un_hbox,vmode+vrule,
  18105.    vmode+accent,vmode+discretionary,vmode+hskip,vmode+valign,
  18106.    vmode+ex_space,vmode+no_boundary:@t@>@;@/
  18107.   begin back_input; new_graf(true);
  18108.   end;
  18109. @ @<Declare act...@>=
  18110. function norm_min(@!h:integer):small_number;
  18111. begin if h<=0 then norm_min:=1@+else if h>=63 then norm_min:=63@+
  18112. else norm_min:=h;
  18113. procedure new_graf(@!indented:boolean);
  18114. begin prev_graf:=0;
  18115. if (mode=vmode)or(head<>tail) then
  18116.   tail_append(new_param_glue(par_skip_code));
  18117. push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
  18118. prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
  18119.              *@'200000+cur_lang;
  18120. if indented then
  18121.   begin tail:=new_null_box; link(head):=tail; width(tail):=par_indent;@+
  18122.   end;
  18123. if every_par<>null then begin_token_list(every_par,every_par_text);
  18124. if nest_ptr=1 then build_page; {put |par_skip| glue on current page}
  18125. @ @<Cases of |main_control| that build...@>=
  18126. hmode+start_par,mmode+start_par: indent_in_hmode;
  18127. @ @<Declare act...@>=
  18128. procedure indent_in_hmode;
  18129. var p,@!q:pointer;
  18130. begin if cur_chr>0 then {\.{\\indent}}
  18131.   begin p:=new_null_box; width(p):=par_indent;
  18132.   if abs(mode)=hmode then space_factor:=1000
  18133.   else  begin q:=new_noad; math_type(nucleus(q)):=sub_box;
  18134.     info(nucleus(q)):=p; p:=q;
  18135.     end;
  18136.   tail_append(p);
  18137.   end;
  18138. @ A paragraph ends when a |par_end| command is sensed, or when we are in
  18139. horizontal mode when reaching the right brace of vertical-mode routines
  18140. like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
  18141. @<Cases of |main_control| that build...@>=
  18142. vmode+par_end: begin normal_paragraph;
  18143.   if mode>0 then build_page;
  18144.   end;
  18145. hmode+par_end: begin if align_state<0 then off_save; {this tries to
  18146.     recover from an alignment that didn't end properly}
  18147.   end_graf; {this takes us to the enclosing mode, if |mode>0|}
  18148.   if mode=vmode then build_page;
  18149.   end;
  18150. hmode+stop,hmode+vskip,hmode+hrule,hmode+un_vbox,hmode+halign: head_for_vmode;
  18151. @ @<Declare act...@>=
  18152. procedure head_for_vmode;
  18153. begin if mode<0 then
  18154.   if cur_cmd<>hrule then off_save
  18155.   else  begin print_err("You can't use `");
  18156.     print_esc("hrule"); print("' here except with leaders");
  18157. @.You can't use \\hrule...@>
  18158.     help2("To put a horizontal rule in an hbox or an alignment,")@/
  18159.       ("you should use \leaders or \hrulefill (see The TeXbook).");
  18160.     error;
  18161.     end
  18162. else  begin back_input; cur_tok:=par_token; back_input; token_type:=inserted;
  18163.   end;
  18164. @ @<Declare act...@>=
  18165. procedure end_graf;
  18166. begin if mode=hmode then
  18167.   begin if head=tail then pop_nest {null paragraphs are ignored}
  18168.   else line_break(widow_penalty);
  18169.   normal_paragraph;
  18170.   error_count:=0;
  18171.   end;
  18172. @ Insertion and adjustment and mark nodes are constructed by the following
  18173. pieces of the program.
  18174. @<Cases of |main_control| that build...@>=
  18175. any_mode(insert),hmode+vadjust,mmode+vadjust: begin_insert_or_adjust;
  18176. any_mode(mark): make_mark;
  18177. @ @<Forbidden...@>=
  18178. vmode+vadjust,
  18179. @ @<Declare act...@>=
  18180. procedure begin_insert_or_adjust;
  18181. begin if cur_cmd=vadjust then cur_val:=255
  18182. else  begin scan_eight_bit_int;
  18183.   if cur_val=255 then
  18184.     begin print_err("You can't "); print_esc("insert"); print_int(255);
  18185. @.You can't \\insert255@>
  18186.     help1("I'm changing to \insert0; box 255 is special.");
  18187.     error; cur_val:=0;
  18188.     end;
  18189.   end;
  18190. saved(0):=cur_val; incr(save_ptr);
  18191. new_save_level(insert_group); scan_left_brace; normal_paragraph;
  18192. push_nest; mode:=-vmode; prev_depth:=ignore_depth;
  18193. @ @<Cases of |handle...@>=
  18194. insert_group: begin end_graf; q:=split_top_skip; add_glue_ref(q);
  18195.   d:=split_max_depth; f:=floating_penalty; unsave; decr(save_ptr);
  18196.   {now |saved(0)| is the insertion number, or 255 for |vadjust|}
  18197.   p:=vpack(link(head),natural); pop_nest;
  18198.   if saved(0)<255 then
  18199.     begin tail_append(get_node(ins_node_size));
  18200.     type(tail):=ins_node; subtype(tail):=qi(saved(0));
  18201.     height(tail):=height(p)+depth(p); ins_ptr(tail):=list_ptr(p);
  18202.     split_top_ptr(tail):=q; depth(tail):=d; float_cost(tail):=f;
  18203.     end
  18204.   else  begin tail_append(get_node(small_node_size));
  18205.     type(tail):=adjust_node;@/
  18206.     subtype(tail):=0; {the |subtype| is not used}
  18207.     adjust_ptr(tail):=list_ptr(p); delete_glue_ref(q);
  18208.     end;
  18209.   free_node(p,box_node_size);
  18210.   if nest_ptr=0 then build_page;
  18211.   end;
  18212. output_group: @<Resume the page builder...@>;
  18213. @ @<Declare act...@>=
  18214. procedure make_mark;
  18215. var p:pointer; {new node}
  18216. begin p:=scan_toks(false,true); p:=get_node(small_node_size);
  18217. type(p):=mark_node; subtype(p):=0; {the |subtype| is not used}
  18218. mark_ptr(p):=def_ref; link(tail):=p; tail:=p;
  18219. @ Penalty nodes get into a list via the |break_penalty| command.
  18220. @^penalties@>
  18221. @<Cases of |main_control| that build...@>=
  18222. any_mode(break_penalty): append_penalty;
  18223. @ @<Declare action...@>=
  18224. procedure append_penalty;
  18225. begin scan_int; tail_append(new_penalty(cur_val));
  18226. if mode=vmode then build_page;
  18227. @ The |remove_item| command removes a penalty, kern, or glue node if it
  18228. appears at the tail of the current list, using a brute-force linear scan.
  18229. Like \.{\\lastbox}, this command is not allowed in vertical mode (except
  18230. internal vertical mode), since the current list in vertical mode is sent
  18231. to the page builder.  But if we happen to be able to implement it in
  18232. vertical mode, we do.
  18233. @<Cases of |main_control| that build...@>=
  18234. any_mode(remove_item): delete_last;
  18235. @ When |delete_last| is called, |cur_chr| is the |type| of node that
  18236. will be deleted, if present.
  18237. @<Declare action...@>=
  18238. procedure delete_last;
  18239. label exit;
  18240. var @!p,@!q:pointer; {run through the current list}
  18241. @!m:quarterword; {the length of a replacement list}
  18242. begin if (mode=vmode)and(tail=head) then
  18243.   @<Apologize for inability to do the operation now,
  18244.     unless \.{\\unskip} follows non-glue@>
  18245. else  begin if not is_char_node(tail) then if type(tail)=cur_chr then
  18246.     begin q:=head;
  18247.     repeat p:=q;
  18248.     if not is_char_node(q) then if type(q)=disc_node then
  18249.       begin for m:=1 to replace_count(q) do p:=link(p);
  18250.       if p=tail then return;
  18251.       end;
  18252.     q:=link(p);
  18253.     until q=tail;
  18254.     link(p):=null; flush_node_list(tail); tail:=p;
  18255.     end;
  18256.   end;
  18257. exit:end;
  18258. @ @<Apologize for inability to do the operation...@>=
  18259. begin if (cur_chr<>glue_node)or(last_glue<>max_halfword) then
  18260.   begin you_cant;
  18261.   help2("Sorry...I usually can't take things from the current page.")@/
  18262.     ("Try `I\vskip-\lastskip' instead.");
  18263.   if cur_chr=kern_node then help_line[0]:=
  18264.     ("Try `I\kern-\lastkern' instead.")
  18265.   else if cur_chr<>glue_node then help_line[0]:=@|
  18266.     ("Perhaps you can make the output routine do it.");
  18267.   error;
  18268.   end;
  18269. @ @<Put each...@>=
  18270. primitive("unpenalty",remove_item,penalty_node);@/
  18271. @!@:un_penalty_}{\.{\\unpenalty} primitive@>
  18272. primitive("unkern",remove_item,kern_node);@/
  18273. @!@:un_kern_}{\.{\\unkern} primitive@>
  18274. primitive("unskip",remove_item,glue_node);@/
  18275. @!@:un_skip_}{\.{\\unskip} primitive@>
  18276. primitive("unhbox",un_hbox,box_code);@/
  18277. @!@:un_hbox_}{\.{\\unhbox} primitive@>
  18278. primitive("unhcopy",un_hbox,copy_code);@/
  18279. @!@:un_hcopy_}{\.{\\unhcopy} primitive@>
  18280. primitive("unvbox",un_vbox,box_code);@/
  18281. @!@:un_vbox_}{\.{\\unvbox} primitive@>
  18282. primitive("unvcopy",un_vbox,copy_code);@/
  18283. @!@:un_vcopy_}{\.{\\unvcopy} primitive@>
  18284. @ @<Cases of |print_cmd_chr|...@>=
  18285. remove_item: if chr_code=glue_node then print_esc("unskip")
  18286.   else if chr_code=kern_node then print_esc("unkern")
  18287.   else print_esc("unpenalty");
  18288. un_hbox: if chr_code=copy_code then print_esc("unhcopy")
  18289.   else print_esc("unhbox");
  18290. un_vbox: if chr_code=copy_code then print_esc("unvcopy")
  18291.   else print_esc("unvbox");
  18292. @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
  18293. @<Cases of |main_control| that build...@>=
  18294. vmode+un_vbox,hmode+un_hbox,mmode+un_hbox: unpackage;
  18295. @ @<Declare act...@>=
  18296. procedure unpackage;
  18297. label exit;
  18298. var p:pointer; {the box}
  18299. @!c:box_code..copy_code; {should we copy?}
  18300. begin c:=cur_chr; scan_eight_bit_int; p:=box(cur_val);
  18301. if p=null then return;
  18302. if (abs(mode)=mmode)or((abs(mode)=vmode)and(type(p)<>vlist_node))or@|
  18303.    ((abs(mode)=hmode)and(type(p)<>hlist_node)) then
  18304.   begin print_err("Incompatible list can't be unboxed");
  18305. @.Incompatible list...@>
  18306.   help3("Sorry, Pandora. (You sneaky devil.)")@/
  18307.   ("I refuse to unbox an \hbox in vertical mode or vice versa.")@/
  18308.   ("And I can't open any boxes in math mode.");@/
  18309.   error; return;
  18310.   end;
  18311. if c=copy_code then link(tail):=copy_node_list(list_ptr(p))
  18312. else  begin link(tail):=list_ptr(p); box(cur_val):=null;
  18313.   free_node(p,box_node_size);
  18314.   end;
  18315. while link(tail)<>null do tail:=link(tail);
  18316. exit:end;
  18317. @ @<Forbidden...@>=vmode+ital_corr,
  18318. @ Italic corrections are converted to kern nodes when the |ital_corr| command
  18319. follows a character. In math mode the same effect is achieved by appending
  18320. a kern of zero here, since italic corrections are supplied later.
  18321. @<Cases of |main_control| that build...@>=
  18322. hmode+ital_corr: append_italic_correction;
  18323. mmode+ital_corr: tail_append(new_kern(0));
  18324. @ @<Declare act...@>=
  18325. procedure append_italic_correction;
  18326. label exit;
  18327. var p:pointer; {|char_node| at the tail of the current list}
  18328. @!f:internal_font_number; {the font in the |char_node|}
  18329. begin if tail<>head then
  18330.   begin if is_char_node(tail) then p:=tail
  18331.   else if type(tail)=ligature_node then p:=lig_char(tail)
  18332.   else return;
  18333.   f:=font(p);
  18334.   tail_append(new_kern(char_italic(f)(char_info(f)(character(p)))));
  18335.   subtype(tail):=explicit;
  18336.   end;
  18337. exit:end;
  18338. @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
  18339. general case we must process three braces full of items.
  18340. @<Put each...@>=
  18341. primitive("-",discretionary,1);
  18342. @!@:Single-character primitives -}{\quad\.{\\-}@>
  18343. primitive("discretionary",discretionary,0);
  18344. @!@:discretionary_}{\.{\\discretionary} primitive@>
  18345. @ @<Cases of |print_cmd_chr|...@>=
  18346. discretionary: if chr_code=1 then
  18347.   print_esc("-")@+else print_esc("discretionary");
  18348. @ @<Cases of |main_control| that build...@>=
  18349. hmode+discretionary,mmode+discretionary: append_discretionary;
  18350. @ The space factor does not change when we append a discretionary node,
  18351. but it starts out as 1000 in the subsidiary lists.
  18352. @<Declare act...@>=
  18353. procedure append_discretionary;
  18354. var c:integer; {hyphen character}
  18355. begin tail_append(new_disc);
  18356. if cur_chr=1 then
  18357.   begin c:=hyphen_char[cur_font];
  18358.   if c>=0 then if c<256 then pre_break(tail):=new_character(cur_font,c);
  18359.   end
  18360. else  begin incr(save_ptr); saved(-1):=0; new_save_level(disc_group);
  18361.   scan_left_brace; push_nest; mode:=-hmode; space_factor:=1000;
  18362.   end;
  18363. @ The three discretionary lists are constructed somewhat as if they were
  18364. hboxes. A~subroutine called |build_discretionary| handles the transitions.
  18365. (This is sort of fun.)
  18366. @<Cases of |handle...@>=
  18367. disc_group: build_discretionary;
  18368. @ @<Declare act...@>=
  18369. procedure build_discretionary;
  18370. label done,exit;
  18371. var p,@!q:pointer; {for link manipulation}
  18372. @!n:integer; {length of discretionary list}
  18373. begin unsave;
  18374. @<Prune the current list, if necessary, until it contains only
  18375.   |char_node|, |kern_node|, |hlist_node|, |vlist_node|, |rule_node|,
  18376.   and |ligature_node| items; set |n| to the length of the list,
  18377.   and set |q| to the list's tail@>;
  18378. p:=link(head); pop_nest;
  18379. case saved(-1) of
  18380. 0:pre_break(tail):=p;
  18381. 1:post_break(tail):=p;
  18382. 2:@<Attach list |p| to the current list, and record its length;
  18383.   then finish up and |return|@>;
  18384. end; {there are no other cases}
  18385. incr(saved(-1)); new_save_level(disc_group); scan_left_brace;
  18386. push_nest; mode:=-hmode; space_factor:=1000;
  18387. exit:end;
  18388. @ @<Attach list |p| to the current...@>=
  18389. begin if (n>0)and(abs(mode)=mmode) then
  18390.   begin print_err("Illegal math "); print_esc("discretionary");
  18391. @.Illegal math \\disc...@>
  18392.   help2("Sorry: The third part of a discretionary break must be")@/
  18393.   ("empty, in math formulas. I had to delete your third part.");
  18394.   flush_node_list(p); n:=0; error;
  18395.   end
  18396. else link(tail):=p;
  18397. if n<=max_quarterword then replace_count(tail):=n
  18398. else  begin print_err("Discretionary list is too long");
  18399. @.Discretionary list is too long@>
  18400.   help2("Wow---I never thought anybody would tweak me here.")@/
  18401.   ("You can't seriously need such a huge discretionary list?");
  18402.   error;
  18403.   end;
  18404. if n>0 then tail:=q;
  18405. decr(save_ptr); return;
  18406. @ During this loop, |p=link(q)| and there are |n| items preceding |p|.
  18407. @<Prune the current list, if necessary...@>=
  18408. q:=head; p:=link(q); n:=0;
  18409. while p<>null do
  18410.   begin if not is_char_node(p) then if type(p)>rule_node then
  18411.     if type(p)<>kern_node then if type(p)<>ligature_node then
  18412.       begin print_err("Improper discretionary list");
  18413. @.Improper discretionary list@>
  18414.       help1("Discretionary lists must contain only boxes and kerns.");@/
  18415.       error;
  18416.       begin_diagnostic;
  18417.       print_nl("The following discretionary sublist has been deleted:");
  18418. @.The following...deleted@>
  18419.       show_box(p);
  18420.       end_diagnostic(true);
  18421.       flush_node_list(p); link(q):=null; goto done;
  18422.       end;
  18423.   q:=p; p:=link(q); incr(n);
  18424.   end;
  18425. done:
  18426. @ We need only one more thing to complete the horizontal mode routines, namely
  18427. the \.{\\accent} primitive.
  18428. @<Cases of |main_control| that build...@>=
  18429. hmode+accent: make_accent;
  18430. @ The positioning of accents is straightforward but tedious. Given an accent
  18431. of width |a|, designed for characters of height |x| and slant |s|;
  18432. and given a character of width |w|, height |h|, and slant |t|: We will shift
  18433. the accent down by |x-h|, and we will insert kern nodes that have the effect of
  18434. centering the accent over the character and shifting the accent to the
  18435. right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$.  If either character is
  18436. absent from the font, we will simply use the other, without shifting.
  18437. @<Declare act...@>=
  18438. procedure make_accent;
  18439. var s,@!t: real; {amount of slant}
  18440. @!p,@!q,@!r:pointer; {character, box, and kern nodes}
  18441. @!f:internal_font_number; {relevant font}
  18442. @!a,@!h,@!x,@!w,@!delta:scaled; {heights and widths, as explained above}
  18443. @!i:four_quarters; {character information}
  18444. begin scan_char_num; f:=cur_font; p:=new_character(f,cur_val);
  18445. if p<>null then
  18446.   begin x:=x_height(f); s:=slant(f)/float_constant(65536);
  18447. @^real division@>
  18448.   a:=char_width(f)(char_info(f)(character(p)));@/
  18449.   do_assignments;@/
  18450.   @<Create a character node |q| for the next character,
  18451.     but set |q:=null| if problems arise@>;
  18452.   if q<>null then @<Append the accent with appropriate kerns,
  18453.       then set |p:=q|@>;
  18454.   link(tail):=p; tail:=p; space_factor:=1000;
  18455.   end;
  18456. @ @<Create a character node |q| for the next...@>=
  18457. q:=null; f:=cur_font;
  18458. if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given) then
  18459.   q:=new_character(f,cur_chr)
  18460. else if cur_cmd=char_num then
  18461.   begin scan_char_num; q:=new_character(f,cur_val);
  18462.   end
  18463. else back_input
  18464. @ The kern nodes appended here must be distinguished from other kerns, lest
  18465. they be wiped away by the hyphenation algorithm or by a previous line break.
  18466. The two kerns are computed with (machine-dependent) |real| arithmetic, but
  18467. their sum is machine-independent; the net effect is machine-independent,
  18468. because the user cannot remove these nodes nor access them via \.{\\lastkern}.
  18469. @<Append the accent with appropriate kerns...@>=
  18470. begin t:=slant(f)/float_constant(65536);
  18471. @^real division@>
  18472. i:=char_info(f)(character(q));
  18473. w:=char_width(f)(i); h:=char_height(f)(height_depth(i));
  18474. if h<>x then {the accent must be shifted up or down}
  18475.   begin p:=hpack(p,natural); shift_amount(p):=x-h;
  18476.   end;
  18477. delta:=round((w-a)/float_constant(2)+h*t-x*s);
  18478. @^real multiplication@>
  18479. @^real addition@>
  18480. r:=new_kern(delta); subtype(r):=acc_kern; link(tail):=r; link(r):=p;
  18481. tail:=new_kern(-a-delta); subtype(tail):=acc_kern; link(p):=tail; p:=q;
  18482. @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
  18483. into |main_control|, it might be that the user has foolishly inserted
  18484. one of them into something that has nothing to do with alignment. But it is
  18485. far more likely that a left brace or right brace has been omitted, since
  18486. |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
  18487. or `\.{\\span}' or tab marks occur with |align_state=0|. The following
  18488. program attempts to make an appropriate recovery.
  18489. @<Cases of |main_control| that build...@>=
  18490. any_mode(car_ret), any_mode(tab_mark): align_error;
  18491. any_mode(no_align): no_align_error;
  18492. any_mode(omit): omit_error;
  18493. @ @<Declare act...@>=
  18494. procedure align_error;
  18495. begin if abs(align_state)>2 then
  18496.   @<Express consternation over the fact that no alignment is in progress@>
  18497. else  begin back_input;
  18498.   if align_state<0 then
  18499.     begin print_err("Missing { inserted");
  18500. @.Missing \{ inserted@>
  18501.     incr(align_state); cur_tok:=left_brace_token+"{";
  18502.     end
  18503.   else  begin print_err("Missing } inserted");
  18504. @.Missing \} inserted@>
  18505.     decr(align_state); cur_tok:=right_brace_token+"}";
  18506.     end;
  18507.   help3("I've put in what seems to be necessary to fix")@/
  18508.     ("the current column of the current alignment.")@/
  18509.     ("Try to go on, since this might almost work."); ins_error;
  18510.   end;
  18511. @ @<Express consternation...@>=
  18512. begin print_err("Misplaced "); print_cmd_chr(cur_cmd,cur_chr);
  18513. @.Misplaced \&@>
  18514. @.Misplaced \\span@>
  18515. @.Misplaced \\cr@>
  18516. if cur_tok=tab_token+"&" then
  18517.   begin help6("I can't figure out why you would want to use a tab mark")@/
  18518.   ("here. If you just want an ampersand, the remedy is")@/
  18519.   ("simple: Just type `I\&' now. But if some right brace")@/
  18520.   ("up above has ended a previous alignment prematurely,")@/
  18521.   ("you're probably due for more error messages, and you")@/
  18522.   ("might try typing `S' now just to see what is salvageable.");
  18523.   end
  18524. else  begin help5("I can't figure out why you would want to use a tab mark")@/
  18525.   ("or \cr or \span just now. If something like a right brace")@/
  18526.   ("up above has ended a previous alignment prematurely,")@/
  18527.   ("you're probably due for more error messages, and you")@/
  18528.   ("might try typing `S' now just to see what is salvageable.");
  18529.   end;
  18530. error;
  18531. @ The help messages here contain a little white lie, since \.{\\noalign}
  18532. and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
  18533. @<Declare act...@>=
  18534. procedure no_align_error;
  18535. begin print_err("Misplaced "); print_esc("noalign");
  18536. @.Misplaced \\noalign@>
  18537. help2("I expect to see \noalign only after the \cr of")@/
  18538.   ("an alignment. Proceed, and I'll ignore this case."); error;
  18539. procedure omit_error;
  18540. begin print_err("Misplaced "); print_esc("omit");
  18541. @.Misplaced \\omit@>
  18542. help2("I expect to see \omit only after tab marks or the \cr of")@/
  18543.   ("an alignment. Proceed, and I'll ignore this case."); error;
  18544. @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
  18545. Let's take a look at what happens when they are used correctly.
  18546. @<Cases of |main_control| that build...@>=
  18547. vmode+halign,hmode+valign:init_align;
  18548. mmode+halign: if privileged then
  18549.   if cur_group=math_shift_group then init_align
  18550.   else off_save;
  18551. vmode+endv,hmode+endv: do_endv;
  18552. @ An |align_group| code is supposed to remain on the |save_stack|
  18553. during an entire alignment, until |fin_align| removes it.
  18554. @<Declare act...@>=
  18555. procedure do_endv;
  18556. begin if cur_group=align_group then
  18557.   begin end_graf;
  18558.   if fin_col then fin_row;
  18559.   end
  18560. else off_save;
  18561. @ @<Cases of |handle_right_brace|...@>=
  18562. align_group: begin back_input; cur_tok:=cs_token_flag+frozen_cr;
  18563.   print_err("Missing "); print_esc("cr"); print(" inserted");
  18564. @.Missing \\cr inserted@>
  18565.   help1("I'm guessing that you meant to end an alignment here.");
  18566.   ins_error;
  18567.   end;
  18568. @ @<Cases of |handle_right_brace|...@>=
  18569. no_align_group: begin end_graf; unsave; align_peek;
  18570.   end;
  18571. @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
  18572. @<Cases of |main_control| that build...@>=
  18573. any_mode(end_cs_name): cs_error;
  18574. @ @<Declare act...@>=
  18575. procedure cs_error;
  18576. begin print_err("Extra "); print_esc("endcsname");
  18577. @.Extra \\endcsname@>
  18578. help1("I'm ignoring this, since I wasn't doing a \csname.");
  18579. error;
  18580. @* \[48] Building math lists.
  18581. The routines that \TeX\ uses to create mlists are similar to those we have
  18582. just seen for the generation of hlists and vlists. But it is necessary to
  18583. make ``noads'' as well as nodes, so the reader should review the
  18584. discussion of math mode data structures before trying to make sense out of
  18585. the following program.
  18586. Here is a little routine that needs to be done whenever a subformula
  18587. is about to be processed. The parameter is a code like |math_group|.
  18588. @<Declare act...@>=
  18589. procedure push_math(@!c:group_code);
  18590. begin push_nest; mode:=-mmode; incompleat_noad:=null; new_save_level(c);
  18591. @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
  18592. |math_shift| character) is scanned. We must check to see whether this
  18593. `\.\$' is immediately followed by another, in case display math mode is
  18594. called for.
  18595. @<Cases of |main_control| that build...@>=
  18596. hmode+math_shift:init_math;
  18597. @ @<Declare act...@>=
  18598. procedure init_math;
  18599. label reswitch,found,not_found,done;
  18600. var w:scaled; {new or partial |pre_display_size|}
  18601. @!l:scaled; {new |display_width|}
  18602. @!s:scaled; {new |display_indent|}
  18603. @!p:pointer; {current node when calculating |pre_display_size|}
  18604. @!q:pointer; {glue specification when calculating |pre_display_size|}
  18605. @!f:internal_font_number; {font in current |char_node|}
  18606. @!n:integer; {scope of paragraph shape specification}
  18607. @!v:scaled; {|w| plus possible glue amount}
  18608. @!d:scaled; {increment to |v|}
  18609. begin get_token; {|get_x_token| would fail on \.{\\ifmmode}\thinspace!}
  18610. if (cur_cmd=math_shift)and(mode>0) then @<Go into display math mode@>
  18611. else  begin back_input; @<Go into ordinary math mode@>;
  18612.   end;
  18613. @ @<Go into ordinary math mode@>=
  18614. begin push_math(math_shift_group); eq_word_define(int_base+cur_fam_code,-1);
  18615. if every_math<>null then begin_token_list(every_math,every_math_text);
  18616. @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
  18617. `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
  18618. the value of |cur_chr| is placed onto |save_stack| for safe keeping.
  18619. @<Cases of |main_control| that build...@>=
  18620. mmode+eq_no: if privileged then
  18621.   if cur_group=math_shift_group then start_eq_no
  18622.   else off_save;
  18623. @ @<Put each...@>=
  18624. primitive("eqno",eq_no,0);
  18625. @!@:eq_no_}{\.{\\eqno} primitive@>
  18626. primitive("leqno",eq_no,1);
  18627. @!@:leq_no_}{\.{\\leqno} primitive@>
  18628. @ When \TeX\ is in display math mode, |cur_group=math_shift_group|,
  18629. so it is not necessary for the |start_eq_no| procedure to test for
  18630. this condition.
  18631. @<Declare act...@>=
  18632. procedure start_eq_no;
  18633. begin saved(0):=cur_chr; incr(save_ptr);
  18634. @<Go into ordinary math mode@>;
  18635. @ @<Cases of |print_cmd_chr|...@>=
  18636. eq_no:if chr_code=1 then print_esc("leqno")@+else print_esc("eqno");
  18637. @ @<Forbidden...@>=non_math(eq_no),
  18638. @ When we enter display math mode, we need to call |line_break| to
  18639. process the partial paragraph that has just been interrupted by the
  18640. display. Then we can set the proper values of |display_width| and
  18641. |display_indent| and |pre_display_size|.
  18642. @<Go into display math mode@>=
  18643. begin if head=tail then {`\.{\\noindent\$\$}' or `\.{\$\${ }\$\$}'}
  18644.   begin pop_nest; w:=-max_dimen;
  18645.   end
  18646. else  begin line_break(display_widow_penalty);@/
  18647.   @<Calculate the natural width, |w|, by which the characters of the
  18648.     final line extend to the right of the reference point,
  18649.     plus two ems; or set |w:=max_dimen| if the non-blank information
  18650.     on that line is affected by stretching or shrinking@>;
  18651.   end;
  18652. {Now we are in vertical mode, working on the list that will contain the display}
  18653. @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
  18654. push_math(math_shift_group); mode:=mmode;
  18655. eq_word_define(int_base+cur_fam_code,-1);@/
  18656. eq_word_define(dimen_base+pre_display_size_code,w);
  18657. eq_word_define(dimen_base+display_width_code,l);
  18658. eq_word_define(dimen_base+display_indent_code,s);
  18659. if every_display<>null then begin_token_list(every_display,every_display_text);
  18660. if nest_ptr=1 then build_page;
  18661. @ @<Calculate the natural width, |w|, by which...@>=
  18662. v:=shift_amount(just_box)+2*quad(cur_font); w:=-max_dimen;
  18663. p:=list_ptr(just_box);
  18664. while p<>null do
  18665.   begin @<Let |d| be the natural width of node |p|;
  18666.     if the node is ``visible,'' |goto found|;
  18667.     if the node is glue that stretches or shrinks, set |v:=max_dimen|@>;
  18668.   if v<max_dimen then v:=v+d;
  18669.   goto not_found;
  18670.   found: if v<max_dimen then
  18671.     begin v:=v+d; w:=v;
  18672.     end
  18673.   else  begin w:=max_dimen; goto done;
  18674.     end;
  18675.   not_found: p:=link(p);
  18676.   end;
  18677. done:
  18678. @ @<Let |d| be the natural width of node |p|...@>=
  18679. reswitch: if is_char_node(p) then
  18680.   begin f:=font(p); d:=char_width(f)(char_info(f)(character(p)));
  18681.   goto found;
  18682.   end;
  18683. case type(p) of
  18684. hlist_node,vlist_node,rule_node: begin d:=width(p); goto found;
  18685.   end;
  18686. ligature_node:@<Make node |p| look like a |char_node|...@>;
  18687. kern_node,math_node: d:=width(p);
  18688. glue_node:@<Let |d| be the natural width of this glue; if stretching
  18689.   or shrinking, set |v:=max_dimen|; |goto found| in the case of leaders@>;
  18690. whatsit_node: @<Let |d| be the width of the whatsit |p|@>;
  18691. othercases d:=0
  18692. endcases
  18693. @ We need to be careful that |w|, |v|, and |d| do not depend on any |glue_set|
  18694. values, since such values are subject to system-dependent rounding.
  18695. System-dependent numbers are not allowed to infiltrate parameters like
  18696. |pre_display_size|, since \TeX82 is supposed to make the same decisions on all
  18697. machines.
  18698. @<Let |d| be the natural width of this glue...@>=
  18699. begin q:=glue_ptr(p); d:=width(q);
  18700. if glue_sign(just_box)=stretching then
  18701.   begin if (glue_order(just_box)=stretch_order(q))and@|
  18702.      (stretch(q)<>0) then
  18703.     v:=max_dimen;
  18704.   end
  18705. else if glue_sign(just_box)=shrinking then
  18706.   begin if (glue_order(just_box)=shrink_order(q))and@|
  18707.      (shrink(q)<>0) then
  18708.     v:=max_dimen;
  18709.   end;
  18710. if subtype(p)>=a_leaders then goto found;
  18711. @ A displayed equation is considered to be three lines long, so we
  18712. calculate the length and offset of line number |prev_graf+2|.
  18713. @<Calculate the length, |l|, ...@>=
  18714. if par_shape_ptr=null then
  18715.   if (hang_indent<>0)and@|
  18716.    (((hang_after>=0)and(prev_graf+2>hang_after))or@|
  18717.     (prev_graf+1<-hang_after)) then
  18718.     begin l:=hsize-abs(hang_indent);
  18719.     if hang_indent>0 then s:=hang_indent@+else s:=0;
  18720.     end
  18721.   else  begin l:=hsize; s:=0;
  18722.     end
  18723. else  begin n:=info(par_shape_ptr);
  18724.   if prev_graf+2>=n then p:=par_shape_ptr+2*n
  18725.   else p:=par_shape_ptr+2*(prev_graf+2);
  18726.   s:=mem[p-1].sc; l:=mem[p].sc;
  18727.   end
  18728. @ Subformulas of math formulas cause a new level of math mode to be entered,
  18729. on the semantic nest as well as the save stack. These subformulas arise in
  18730. several ways: (1)~A left brace by itself indicates the beginning of a
  18731. subformula that will be put into a box, thereby freezing its glue and
  18732. preventing line breaks. (2)~A subscript or superscript is treated as a
  18733. subformula if it is not a single character; the same applies to
  18734. the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
  18735. initiates a subformula that will be terminated by a matching \.{\\right}.
  18736. The group codes placed on |save_stack| in these three cases are
  18737. |math_group|, |math_group|, and |math_left_group|, respectively.
  18738. Here is the code that handles case (1); the other cases are not quite as
  18739. trivial, so we shall consider them later.
  18740. @<Cases of |main_control| that build...@>=
  18741. mmode+left_brace: begin tail_append(new_noad);
  18742.   back_input; scan_math(nucleus(tail));
  18743.   end;
  18744. @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
  18745. broken down into subfields called |math_type| and either |info| or
  18746. |(fam,character)|. The job of |scan_math| is to figure out what to place
  18747. in one of these principal fields; it looks at the subformula that
  18748. comes next in the input, and places an encoding of that subformula
  18749. into a given word of |mem|.
  18750. @d fam_in_range==((cur_fam>=0)and(cur_fam<16))
  18751. @<Declare act...@>=
  18752. procedure scan_math(@!p:pointer);
  18753. label restart,reswitch,exit;
  18754. var c:integer; {math character code}
  18755. begin restart:@<Get the next non-blank non-relax...@>;
  18756. reswitch:case cur_cmd of
  18757. letter,other_char,char_given: begin c:=ho(math_code(cur_chr));
  18758.     if c=@'100000 then
  18759.       begin @<Treat |cur_chr| as an active character@>;
  18760.       goto restart;
  18761.       end;
  18762.     end;
  18763. char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
  18764.   goto reswitch;
  18765.   end;
  18766. math_char_num: begin scan_fifteen_bit_int; c:=cur_val;
  18767.   end;
  18768. math_given: c:=cur_chr;
  18769. delim_num: begin scan_twenty_seven_bit_int; c:=cur_val div @'10000;
  18770.   end;
  18771. othercases @<Scan a subformula enclosed in braces and |return|@>
  18772. endcases;@/
  18773. math_type(p):=math_char; character(p):=qi(c mod 256);
  18774. if (c>=var_code)and fam_in_range then fam(p):=cur_fam
  18775. else fam(p):=(c div 256) mod 16;
  18776. exit:end;
  18777. @ An active character that is an |outer_call| is allowed here.
  18778. @<Treat |cur_chr|...@>=
  18779. begin cur_cs:=cur_chr+active_base;
  18780. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  18781. x_token; back_input;
  18782. @ The pointer |p| is placed on |save_stack| while a complex subformula
  18783. is being scanned.
  18784. @<Scan a subformula...@>=
  18785. begin back_input; scan_left_brace;@/
  18786. saved(0):=p; incr(save_ptr); push_math(math_group); return;
  18787. @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
  18788. generated. The next simplest cases involve a single character, e.g.,
  18789. `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
  18790. the reader can perhaps understand how happy the author was when `\.{\$x\$}'
  18791. was first properly typeset by \TeX. The code in this section was used.
  18792. @^Knuth, Donald Ervin@>
  18793. @<Cases of |main_control| that build...@>=
  18794. mmode+letter,mmode+other_char,mmode+char_given:
  18795.   set_math_char(ho(math_code(cur_chr)));
  18796. mmode+char_num: begin scan_char_num; cur_chr:=cur_val;
  18797.   set_math_char(ho(math_code(cur_chr)));
  18798.   end;
  18799. mmode+math_char_num: begin scan_fifteen_bit_int; set_math_char(cur_val);
  18800.   end;
  18801. mmode+math_given: set_math_char(cur_chr);
  18802. mmode+delim_num: begin scan_twenty_seven_bit_int;
  18803.   set_math_char(cur_val div @'10000);
  18804.   end;
  18805. @ The |set_math_char| procedure creates a new noad appropriate to a given
  18806. math code, and appends it to the current mlist. However, if the math code
  18807. is sufficiently large, the |cur_chr| is treated as an active character and
  18808. nothing is appended.
  18809. @<Declare act...@>=
  18810. procedure set_math_char(@!c:integer);
  18811. var p:pointer; {the new noad}
  18812. begin if c>=@'100000 then
  18813.   @<Treat |cur_chr|...@>
  18814. else  begin p:=new_noad; math_type(nucleus(p)):=math_char;
  18815.   character(nucleus(p)):=qi(c mod 256);
  18816.   fam(nucleus(p)):=(c div 256) mod 16;
  18817.   if c>=var_code then
  18818.     begin if fam_in_range then fam(nucleus(p)):=cur_fam;
  18819.     type(p):=ord_noad;
  18820.     end
  18821.   else  type(p):=ord_noad+(c div @'10000);
  18822.   link(tail):=p; tail:=p;
  18823.   end;
  18824. @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
  18825. the command code |math_comp|, supplemented by the noad type that they
  18826. generate.
  18827. @<Put each...@>=
  18828. primitive("mathord",math_comp,ord_noad);
  18829. @!@:math_ord_}{\.{\\mathord} primitive@>
  18830. primitive("mathop",math_comp,op_noad);
  18831. @!@:math_op_}{\.{\\mathop} primitive@>
  18832. primitive("mathbin",math_comp,bin_noad);
  18833. @!@:math_bin_}{\.{\\mathbin} primitive@>
  18834. primitive("mathrel",math_comp,rel_noad);
  18835. @!@:math_rel_}{\.{\\mathrel} primitive@>
  18836. primitive("mathopen",math_comp,open_noad);
  18837. @!@:math_open_}{\.{\\mathopen} primitive@>
  18838. primitive("mathclose",math_comp,close_noad);
  18839. @!@:math_close_}{\.{\\mathclose} primitive@>
  18840. primitive("mathpunct",math_comp,punct_noad);
  18841. @!@:math_punct_}{\.{\\mathpunct} primitive@>
  18842. primitive("mathinner",math_comp,inner_noad);
  18843. @!@:math_inner_}{\.{\\mathinner} primitive@>
  18844. primitive("underline",math_comp,under_noad);
  18845. @!@:underline_}{\.{\\underline} primitive@>
  18846. primitive("overline",math_comp,over_noad);@/
  18847. @!@:overline_}{\.{\\overline} primitive@>
  18848. primitive("displaylimits",limit_switch,normal);
  18849. @!@:display_limits_}{\.{\\displaylimits} primitive@>
  18850. primitive("limits",limit_switch,limits);
  18851. @!@:limits_}{\.{\\limits} primitive@>
  18852. primitive("nolimits",limit_switch,no_limits);
  18853. @!@:no_limits_}{\.{\\nolimits} primitive@>
  18854. @ @<Cases of |print_cmd_chr|...@>=
  18855. math_comp: case chr_code of
  18856.   ord_noad: print_esc("mathord");
  18857.   op_noad: print_esc("mathop");
  18858.   bin_noad: print_esc("mathbin");
  18859.   rel_noad: print_esc("mathrel");
  18860.   open_noad: print_esc("mathopen");
  18861.   close_noad: print_esc("mathclose");
  18862.   punct_noad: print_esc("mathpunct");
  18863.   inner_noad: print_esc("mathinner");
  18864.   under_noad: print_esc("underline");
  18865.   othercases print_esc("overline")
  18866.   endcases;
  18867. limit_switch: if chr_code=limits then print_esc("limits")
  18868.   else if chr_code=no_limits then print_esc("nolimits")
  18869.   else print_esc("displaylimits");
  18870. @ @<Cases of |main_control| that build...@>=
  18871. mmode+math_comp: begin tail_append(new_noad);
  18872.   type(tail):=cur_chr; scan_math(nucleus(tail));
  18873.   end;
  18874. mmode+limit_switch: math_limit_switch;
  18875. @ @<Declare act...@>=
  18876. procedure math_limit_switch;
  18877. label exit;
  18878. begin if head<>tail then if type(tail)=op_noad then
  18879.   begin subtype(tail):=cur_chr; return;
  18880.   end;
  18881. print_err("Limit controls must follow a math operator");
  18882. @.Limit controls must follow...@>
  18883. help1("I'm ignoring this misplaced \limits or \nolimits command."); error;
  18884. exit:end;
  18885. @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
  18886. The first parameter of this procedure is the |mem| address where the
  18887. delimiter is to be placed; the second tells if this delimiter follows
  18888. \.{\\radical} or not.
  18889. @<Declare act...@>=
  18890. procedure scan_delimiter(@!p:pointer;@!r:boolean);
  18891. begin if r then scan_twenty_seven_bit_int
  18892. else  begin @<Get the next non-blank non-relax...@>;
  18893.   case cur_cmd of
  18894.   letter,other_char: cur_val:=del_code(cur_chr);
  18895.   delim_num: scan_twenty_seven_bit_int;
  18896.   othercases cur_val:=-1
  18897.   endcases;
  18898.   end;
  18899. if cur_val<0 then @<Report that an invalid delimiter code is being changed
  18900.    to null; set~|cur_val:=0|@>;
  18901. small_fam(p):=(cur_val div @'4000000) mod 16;
  18902. small_char(p):=qi((cur_val div @'10000) mod 256);
  18903. large_fam(p):=(cur_val div 256) mod 16;
  18904. large_char(p):=qi(cur_val mod 256);
  18905. @ @<Report that an invalid delimiter...@>=
  18906. begin print_err("Missing delimiter (. inserted)");
  18907. @.Missing delimiter...@>
  18908. help6("I was expecting to see something like `(' or `\{' or")@/
  18909.   ("`\}' here. If you typed, e.g., `{' instead of `\{', you")@/
  18910.   ("should probably delete the `{' by typing `1' now, so that")@/
  18911.   ("braces don't get unbalanced. Otherwise just proceed.")@/
  18912.   ("Acceptable delimiters are characters whose \delcode is")@/
  18913.   ("nonnegative, or you can use `\delimiter <delimiter code>'.");
  18914. back_error; cur_val:=0;
  18915. @ @<Cases of |main_control| that build...@>=
  18916. mmode+radical:math_radical;
  18917. @ @<Declare act...@>=
  18918. procedure math_radical;
  18919. begin tail_append(get_node(radical_noad_size));
  18920. type(tail):=radical_noad; subtype(tail):=normal;
  18921. mem[nucleus(tail)].hh:=empty_field;
  18922. mem[subscr(tail)].hh:=empty_field;
  18923. mem[supscr(tail)].hh:=empty_field;
  18924. scan_delimiter(left_delimiter(tail),true); scan_math(nucleus(tail));
  18925. @ @<Cases of |main_control| that build...@>=
  18926. mmode+accent,mmode+math_accent:math_ac;
  18927. @ @<Declare act...@>=
  18928. procedure math_ac;
  18929. begin if cur_cmd=accent then
  18930.   @<Complain that the user should have said \.{\\mathaccent}@>;
  18931. tail_append(get_node(accent_noad_size));
  18932. type(tail):=accent_noad; subtype(tail):=normal;
  18933. mem[nucleus(tail)].hh:=empty_field;
  18934. mem[subscr(tail)].hh:=empty_field;
  18935. mem[supscr(tail)].hh:=empty_field;
  18936. math_type(accent_chr(tail)):=math_char;
  18937. scan_fifteen_bit_int;
  18938. character(accent_chr(tail)):=qi(cur_val mod 256);
  18939. if (cur_val>=var_code)and fam_in_range then fam(accent_chr(tail)):=cur_fam
  18940. else fam(accent_chr(tail)):=(cur_val div 256) mod 16;
  18941. scan_math(nucleus(tail));
  18942. @ @<Complain that the user should have said \.{\\mathaccent}@>=
  18943. begin print_err("Please use "); print_esc("mathaccent");
  18944. print(" for accents in math mode");
  18945. @.Please use \\mathaccent...@>
  18946. help2("I'm changing \accent to \mathaccent here; wish me luck.")@/
  18947.   ("(Accents are not the same in formulas as they are in text.)");
  18948. error;
  18949. @ @<Cases of |main_control| that build...@>=
  18950. mmode+vcenter: begin scan_spec(vcenter_group,false); normal_paragraph;
  18951.   push_nest; mode:=-vmode; prev_depth:=ignore_depth;
  18952.   if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
  18953.   end;
  18954. @ @<Cases of |handle...@>=
  18955. vcenter_group: begin end_graf; unsave; save_ptr:=save_ptr-2;
  18956.   p:=vpack(link(head),saved(1),saved(0)); pop_nest;
  18957.   tail_append(new_noad); type(tail):=vcenter_noad;
  18958.   math_type(nucleus(tail)):=sub_box; info(nucleus(tail)):=p;
  18959.   end;
  18960. @ The routine that inserts a |style_node| holds no surprises.
  18961. @<Put each...@>=
  18962. primitive("displaystyle",math_style,display_style);
  18963. @!@:display_style_}{\.{\\displaystyle} primitive@>
  18964. primitive("textstyle",math_style,text_style);
  18965. @!@:text_style_}{\.{\\textstyle} primitive@>
  18966. primitive("scriptstyle",math_style,script_style);
  18967. @!@:script_style_}{\.{\\scriptstyle} primitive@>
  18968. primitive("scriptscriptstyle",math_style,script_script_style);
  18969. @!@:script_script_style_}{\.{\\scriptscriptstyle} primitive@>
  18970. @ @<Cases of |print_cmd_chr|...@>=
  18971. math_style: print_style(chr_code);
  18972. @ @<Cases of |main_control| that build...@>=
  18973. mmode+math_style: tail_append(new_style(cur_chr));
  18974. mmode+non_script: begin tail_append(new_glue(zero_glue));
  18975.   subtype(tail):=cond_math_glue;
  18976.   end;
  18977. mmode+math_choice: append_choices;
  18978. @ The routine that scans the four mlists of a \.{\\mathchoice} is very
  18979. much like the routine that builds discretionary nodes.
  18980. @<Declare act...@>=
  18981. procedure append_choices;
  18982. begin tail_append(new_choice); incr(save_ptr); saved(-1):=0;
  18983. push_math(math_choice_group); scan_left_brace;
  18984. @ @<Cases of |handle_right_brace|...@>=
  18985. math_choice_group: build_choices;
  18986. @ @<Declare act...@>=
  18987. @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
  18988. procedure build_choices;
  18989. label exit;
  18990. var p:pointer; {the current mlist}
  18991. begin unsave; p:=fin_mlist(null);
  18992. case saved(-1) of
  18993. 0:display_mlist(tail):=p;
  18994. 1:text_mlist(tail):=p;
  18995. 2:script_mlist(tail):=p;
  18996. 3:begin script_script_mlist(tail):=p; decr(save_ptr); return;
  18997.   end;
  18998. end; {there are no other cases}
  18999. incr(saved(-1)); push_math(math_choice_group); scan_left_brace;
  19000. exit:end;
  19001. @ Subscripts and superscripts are attached to the previous nucleus by the
  19002. @^superscripts@>@^subscripts@>
  19003. action procedure called |sub_sup|. We use the facts that |sub_mark=sup_mark+1|
  19004. and |subscr(p)=supscr(p)+1|.
  19005. @<Cases of |main_control| that build...@>=
  19006. mmode+sub_mark,mmode+sup_mark: sub_sup;
  19007. @ @<Declare act...@>=
  19008. procedure sub_sup;
  19009. var t:small_number; {type of previous sub/superscript}
  19010. @!p:pointer; {field to be filled by |scan_math|}
  19011. begin t:=empty; p:=null;
  19012. if tail<>head then if scripts_allowed(tail) then
  19013.   begin p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
  19014.   t:=math_type(p);
  19015.   end;
  19016. if (p=null)or(t<>empty) then @<Insert a dummy noad to be sub/superscripted@>;
  19017. scan_math(p);
  19018. @ @<Insert a dummy...@>=
  19019. begin tail_append(new_noad);
  19020. p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
  19021. if t<>empty then
  19022.   begin if cur_cmd=sup_mark then
  19023.     begin print_err("Double superscript");
  19024. @.Double superscript@>
  19025.     help1("I treat `x^1^2' essentially like `x^1{}^2'.");
  19026.     end
  19027.   else  begin print_err("Double subscript");
  19028. @.Double subscript@>
  19029.     help1("I treat `x_1_2' essentially like `x_1{}_2'.");
  19030.     end;
  19031.   error;
  19032.   end;
  19033. @ An operation like `\.{\\over}' causes the current mlist to go into a
  19034. state of suspended animation: |incompleat_noad| points to a |fraction_noad|
  19035. that contains the mlist-so-far as its numerator, while the denominator
  19036. is yet to come. Finally when the mlist is finished, the denominator will
  19037. go into the incompleat fraction noad, and that noad will become the
  19038. whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
  19039. delimiters.
  19040. @d above_code=0 { `\.{\\above}' }
  19041. @d over_code=1 { `\.{\\over}' }
  19042. @d atop_code=2 { `\.{\\atop}' }
  19043. @d delimited_code=3 { `\.{\\abovewithdelims}', etc.}
  19044. @<Put each...@>=
  19045. primitive("above",above,above_code);@/
  19046. @!@:above_}{\.{\\above} primitive@>
  19047. primitive("over",above,over_code);@/
  19048. @!@:over_}{\.{\\over} primitive@>
  19049. primitive("atop",above,atop_code);@/
  19050. @!@:atop_}{\.{\\atop} primitive@>
  19051. primitive("abovewithdelims",above,delimited_code+above_code);@/
  19052. @!@:above_with_delims_}{\.{\\abovewithdelims} primitive@>
  19053. primitive("overwithdelims",above,delimited_code+over_code);@/
  19054. @!@:over_with_delims_}{\.{\\overwithdelims} primitive@>
  19055. primitive("atopwithdelims",above,delimited_code+atop_code);
  19056. @!@:atop_with_delims_}{\.{\\atopwithdelims} primitive@>
  19057. @ @<Cases of |print_cmd_chr|...@>=
  19058. above: case chr_code of
  19059.   over_code:print_esc("over");
  19060.   atop_code:print_esc("atop");
  19061.   delimited_code+above_code:print_esc("abovewithdelims");
  19062.   delimited_code+over_code:print_esc("overwithdelims");
  19063.   delimited_code+atop_code:print_esc("atopwithdelims");
  19064.   othercases print_esc("above")
  19065.   endcases;
  19066. @ @<Cases of |main_control| that build...@>=
  19067. mmode+above: math_fraction;
  19068. @ @<Declare act...@>=
  19069. procedure math_fraction;
  19070. var c:small_number; {the type of generalized fraction we are scanning}
  19071. begin c:=cur_chr;
  19072. if incompleat_noad<>null then
  19073.   @<Ignore the fraction operation and complain about this ambiguous case@>
  19074. else  begin incompleat_noad:=get_node(fraction_noad_size);
  19075.   type(incompleat_noad):=fraction_noad;
  19076.   subtype(incompleat_noad):=normal;
  19077.   math_type(numerator(incompleat_noad)):=sub_mlist;
  19078.   info(numerator(incompleat_noad)):=link(head);
  19079.   mem[denominator(incompleat_noad)].hh:=empty_field;
  19080.   mem[left_delimiter(incompleat_noad)].qqqq:=null_delimiter;
  19081.   mem[right_delimiter(incompleat_noad)].qqqq:=null_delimiter;@/
  19082.   link(head):=null; tail:=head;
  19083.   @<Use code |c| to distinguish between generalized fractions@>;
  19084.   end;
  19085. @ @<Use code |c|...@>=
  19086. if c>=delimited_code then
  19087.   begin scan_delimiter(left_delimiter(incompleat_noad),false);
  19088.   scan_delimiter(right_delimiter(incompleat_noad),false);
  19089.   end;
  19090. case c mod delimited_code of
  19091. above_code: begin scan_normal_dimen;
  19092.   thickness(incompleat_noad):=cur_val;
  19093.   end;
  19094. over_code: thickness(incompleat_noad):=default_code;
  19095. atop_code: thickness(incompleat_noad):=0;
  19096. end {there are no other cases}
  19097. @ @<Ignore the fraction...@>=
  19098. begin if c>=delimited_code then
  19099.   begin scan_delimiter(garbage,false); scan_delimiter(garbage,false);
  19100.   end;
  19101. if c mod delimited_code=above_code then scan_normal_dimen;
  19102. print_err("Ambiguous; you need another { and }");
  19103. @.Ambiguous...@>
  19104. help3("I'm ignoring this fraction specification, since I don't")@/
  19105.   ("know whether a construction like `x \over y \over z'")@/
  19106.   ("means `{x \over y} \over z' or `x \over {y \over z}'.");
  19107. error;
  19108. @ At the end of a math formula or subformula, the |fin_mlist| routine is
  19109. called upon to return a pointer to the newly completed mlist, and to
  19110. pop the nest back to the enclosing semantic level. The parameter to
  19111. |fin_mlist|, if not null, points to a |right_noad| that ends the
  19112. current mlist; this |right_noad| has not yet been appended.
  19113. @<Declare the function called |fin_mlist|@>=
  19114. function fin_mlist(@!p:pointer):pointer;
  19115. var q:pointer; {the mlist to return}
  19116. begin if incompleat_noad<>null then @<Compleat the incompleat noad@>
  19117. else  begin link(tail):=p; q:=link(head);
  19118.   end;
  19119. pop_nest; fin_mlist:=q;
  19120. @ @<Compleat...@>=
  19121. begin math_type(denominator(incompleat_noad)):=sub_mlist;
  19122. info(denominator(incompleat_noad)):=link(head);
  19123. if p=null then q:=incompleat_noad
  19124. else  begin q:=info(numerator(incompleat_noad));
  19125.   if type(q)<>left_noad then confusion("right");
  19126. @:this can't happen right}{\quad right@>
  19127.   info(numerator(incompleat_noad)):=link(q);
  19128.   link(q):=incompleat_noad; link(incompleat_noad):=p;
  19129.   end;
  19130. @ Now at last we're ready to see what happens when a right brace occurs
  19131. in a math formula. Two special cases are simplified here: Braces are effectively
  19132. removed when they surround a single Ord without sub/superscripts, or when they
  19133. surround an accent that is the nucleus of an Ord atom.
  19134. @<Cases of |handle...@>=
  19135. math_group: begin unsave; decr(save_ptr);@/
  19136.   math_type(saved(0)):=sub_mlist; p:=fin_mlist(null); info(saved(0)):=p;
  19137.   if p<>null then if link(p)=null then
  19138.    if type(p)=ord_noad then
  19139.     begin if math_type(subscr(p))=empty then
  19140.      if math_type(supscr(p))=empty then
  19141.       begin mem[saved(0)].hh:=mem[nucleus(p)].hh;
  19142.       free_node(p,noad_size);
  19143.       end;
  19144.     end
  19145.   else if type(p)=accent_noad then if saved(0)=nucleus(tail) then
  19146.    if type(tail)=ord_noad then @<Replace the tail of the list by |p|@>;
  19147.   end;
  19148. @ @<Replace the tail...@>=
  19149. begin q:=head; while link(q)<>tail do q:=link(q);
  19150. link(q):=p; free_node(tail,noad_size); tail:=p;
  19151. @ We have dealt with all constructions of math mode except `\.{\\left}' and
  19152. `\.{\\right}', so the picture is completed by the following sections of
  19153. the program.
  19154. @<Put each...@>=
  19155. primitive("left",left_right,left_noad);
  19156. @!@:left_}{\.{\\left} primitive@>
  19157. primitive("right",left_right,right_noad);
  19158. @!@:right_}{\.{\\right} primitive@>
  19159. text(frozen_right):="right"; eqtb[frozen_right]:=eqtb[cur_val];
  19160. @ @<Cases of |print_cmd_chr|...@>=
  19161. left_right: if chr_code=left_noad then print_esc("left")
  19162. else print_esc("right");
  19163. @ @<Cases of |main_control| that build...@>=
  19164. mmode+left_right: math_left_right;
  19165. @ @<Declare act...@>=
  19166. procedure math_left_right;
  19167. var t:small_number; {|left_noad| or |right_noad|}
  19168. @!p:pointer; {new noad}
  19169. begin t:=cur_chr;
  19170. if (t=right_noad)and(cur_group<>math_left_group) then
  19171.   @<Try to recover from mismatched \.{\\right}@>
  19172. else  begin p:=new_noad; type(p):=t;
  19173.   scan_delimiter(delimiter(p),false);
  19174.   if t=left_noad then
  19175.     begin push_math(math_left_group); link(head):=p; tail:=p;
  19176.     end
  19177.   else  begin p:=fin_mlist(p); unsave; {end of |math_left_group|}
  19178.     tail_append(new_noad); type(tail):=inner_noad;
  19179.     math_type(nucleus(tail)):=sub_mlist;
  19180.     info(nucleus(tail)):=p;
  19181.     end;
  19182.   end;
  19183. @ @<Try to recover from mismatch...@>=
  19184. begin if cur_group=math_shift_group then
  19185.   begin scan_delimiter(garbage,false);
  19186.   print_err("Extra "); print_esc("right");
  19187. @.Extra \\right.@>
  19188.   help1("I'm ignoring a \right that had no matching \left.");
  19189.   error;
  19190.   end
  19191. else off_save;
  19192. @ Here is the only way out of math mode.
  19193. @<Cases of |main_control| that build...@>=
  19194. mmode+math_shift: if cur_group=math_shift_group then after_math
  19195.   else off_save;
  19196. @ @<Declare act...@>=
  19197. procedure after_math;
  19198. var l:boolean; {`\.{\\leqno}' instead of `\.{\\eqno}'}
  19199. @!danger:boolean; {not enough symbol fonts are present}
  19200. @!m:integer; {|mmode| or |-mmode|}
  19201. @!p:pointer; {the formula}
  19202. @!a:pointer; {box containing equation number}
  19203. @<Local variables for finishing a displayed formula@>@;
  19204. begin danger:=false;
  19205. @<Check that the necessary fonts for math symbols are present;
  19206.   if not, flush the current math lists and set |danger:=true|@>;
  19207. m:=mode; l:=false; p:=fin_mlist(null); {this pops the nest}
  19208. if mode=-m then {end of equation number}
  19209.   begin @<Check that another \.\$ follows@>;
  19210.   cur_mlist:=p; cur_style:=text_style; mlist_penalties:=false;
  19211.   mlist_to_hlist; a:=hpack(link(temp_head),natural);
  19212.   unsave; decr(save_ptr); {now |cur_group=math_shift_group|}
  19213.   if saved(0)=1 then l:=true;
  19214.   danger:=false;
  19215.   @<Check that the necessary fonts for math symbols are present;
  19216.     if not, flush the current math lists and set |danger:=true|@>;
  19217.   m:=mode; p:=fin_mlist(null);
  19218.   end
  19219. else a:=null;
  19220. if m<0 then @<Finish math in text@>
  19221. else  begin if a=null then @<Check that another \.\$ follows@>;
  19222.   @<Finish displayed math@>;
  19223.   end;
  19224. @ @<Check that the necessary fonts...@>=
  19225. if (font_params[fam_fnt(2+text_size)]<total_mathsy_params)or@|
  19226.    (font_params[fam_fnt(2+script_size)]<total_mathsy_params)or@|
  19227.    (font_params[fam_fnt(2+script_script_size)]<total_mathsy_params) then
  19228.   begin print_err("Math formula deleted: Insufficient symbol fonts");@/
  19229. @.Math formula deleted...@>
  19230.   help3("Sorry, but I can't typeset math unless \textfont 2")@/
  19231.     ("and \scriptfont 2 and \scriptscriptfont 2 have all")@/
  19232.     ("the \fontdimen values needed in math symbol fonts.");
  19233.   error; flush_math; danger:=true;
  19234.   end
  19235. else if (font_params[fam_fnt(3+text_size)]<total_mathex_params)or@|
  19236.    (font_params[fam_fnt(3+script_size)]<total_mathex_params)or@|
  19237.    (font_params[fam_fnt(3+script_script_size)]<total_mathex_params) then
  19238.   begin print_err("Math formula deleted: Insufficient extension fonts");@/
  19239.   help3("Sorry, but I can't typeset math unless \textfont 3")@/
  19240.     ("and \scriptfont 3 and \scriptscriptfont 3 have all")@/
  19241.     ("the \fontdimen values needed in math extension fonts.");
  19242.   error; flush_math; danger:=true;
  19243.   end
  19244. @ The |unsave| is done after everything else here; hence an appearance of
  19245. `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
  19246. particular \.\$'s. This is consistent with the conventions of
  19247. `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
  19248. space above that display.
  19249. @<Finish math in text@>=
  19250. begin tail_append(new_math(math_surround,before));
  19251. cur_mlist:=p; cur_style:=text_style; mlist_penalties:=(mode>0); mlist_to_hlist;
  19252. link(tail):=link(temp_head);
  19253. while link(tail)<>null do tail:=link(tail);
  19254. tail_append(new_math(math_surround,after));
  19255. space_factor:=1000; unsave;
  19256. @ \TeX\ gets to the following part of the program when the first `\.\$' ending
  19257. a display has been scanned.
  19258. @<Check that another \.\$ follows@>=
  19259. begin get_x_token;
  19260. if cur_cmd<>math_shift then
  19261.   begin print_err("Display math should end with $$");
  19262. @.Display math...with \$\$@>
  19263.   help2("The `$' that I just saw supposedly matches a previous `$$'.")@/
  19264.     ("So I shall assume that you typed `$$' both times.");
  19265.   back_error;
  19266.   end;
  19267. @ We have saved the worst for last: The fussiest part of math mode processing
  19268. occurs when a displayed formula is being centered and placed with an optional
  19269. equation number.
  19270. @<Local variables for finishing...@>=
  19271. @!b:pointer; {box containing the equation}
  19272. @!w:scaled; {width of the equation}
  19273. @!z:scaled; {width of the line}
  19274. @!e:scaled; {width of equation number}
  19275. @!q:scaled; {width of equation number plus space to separate from equation}
  19276. @!d:scaled; {displacement of equation in the line}
  19277. @!s:scaled; {move the line right this much}
  19278. @!g1,@!g2:small_number; {glue parameter codes for before and after}
  19279. @!r:pointer; {kern node used to position the display}
  19280. @!t:pointer; {tail of adjustment list}
  19281. @ At this time |p| points to the mlist for the formula; |a| is either
  19282. |null| or it points to a box containing the equation number; and we are in
  19283. vertical mode (or internal vertical mode).
  19284. @<Finish displayed math@>=
  19285. cur_mlist:=p; cur_style:=display_style; mlist_penalties:=false;
  19286. mlist_to_hlist; p:=link(temp_head);@/
  19287. adjust_tail:=adjust_head; b:=hpack(p,natural); p:=list_ptr(b);
  19288. t:=adjust_tail; adjust_tail:=null;@/
  19289. w:=width(b); z:=display_width; s:=display_indent;
  19290. if (a=null)or danger then
  19291.   begin e:=0; q:=0;
  19292.   end
  19293. else  begin e:=width(a); q:=e+math_quad(text_size);
  19294.   end;
  19295. if w+q>z then
  19296.   @<Squeeze the equation as much as possible; if there is an equation
  19297.     number that should go on a separate line by itself,
  19298.     set~|e:=0|@>;
  19299. @<Determine the displacement, |d|, of the left edge of the equation, with
  19300.   respect to the line size |z|, assuming that |l=false|@>;
  19301. @<Append the glue or equation number preceding the display@>;
  19302. @<Append the display and perhaps also the equation number@>;
  19303. @<Append the glue or equation number following the display@>;
  19304. resume_after_display
  19305. @ @<Declare act...@>=
  19306. procedure resume_after_display;
  19307. begin if cur_group<>math_shift_group then confusion("display");
  19308. @:this can't happen display}{\quad display@>
  19309. unsave; prev_graf:=prev_graf+3;
  19310. push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
  19311. prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
  19312.              *@'200000+cur_lang;
  19313. @<Scan an optional space@>;
  19314. if nest_ptr=1 then build_page;
  19315. @ The user can force the equation number to go on a separate line
  19316. by causing its width to be zero.
  19317. @<Squeeze the equation as much as possible...@>=
  19318. begin if (e<>0)and((w-total_shrink[normal]+q<=z)or@|
  19319.    (total_shrink[fil]<>0)or(total_shrink[fill]<>0)or
  19320.    (total_shrink[filll]<>0)) then
  19321.   begin free_node(b,box_node_size);
  19322.   b:=hpack(p,z-q,exactly);
  19323.   end
  19324. else  begin e:=0;
  19325.   if w>z then
  19326.     begin free_node(b,box_node_size);
  19327.     b:=hpack(p,z,exactly);
  19328.     end;
  19329.   end;
  19330. w:=width(b);
  19331. @ We try first to center the display without regard to the existence of
  19332. the equation number. If that would make it too close (where ``too close''
  19333. means that the space between display and equation number is less than the
  19334. width of the equation number), we either center it in the remaining space
  19335. or move it as far from the equation number as possible. The latter alternative
  19336. is taken only if the display begins with glue, since we assume that the
  19337. user put glue there to control the spacing precisely.
  19338. @<Determine the displacement, |d|, of the left edge of the equation...@>=
  19339. d:=half(z-w);
  19340. if (e>0)and(d<2*e) then {too close}
  19341.   begin d:=half(z-w-e);
  19342.   if p<>null then if not is_char_node(p) then if type(p)=glue_node then d:=0;
  19343.   end
  19344. @ If the equation number is set on a line by itself, either before or
  19345. after the formula, we append an infinite penalty so that no page break will
  19346. separate the display from its number; and we use the same size and
  19347. displacement for all three potential lines of the display, even though
  19348. `\.{\\parshape}' may specify them differently.
  19349. @<Append the glue or equation number preceding the display@>=
  19350. tail_append(new_penalty(pre_display_penalty));@/
  19351. if (d+s<=pre_display_size)or l then {not enough clearance}
  19352.   begin g1:=above_display_skip_code; g2:=below_display_skip_code;
  19353.   end
  19354. else  begin g1:=above_display_short_skip_code;
  19355.   g2:=below_display_short_skip_code;
  19356.   end;
  19357. if l and(e=0) then {it follows that |type(a)=hlist_node|}
  19358.   begin shift_amount(a):=s; append_to_vlist(a);
  19359.   tail_append(new_penalty(inf_penalty));
  19360.   end
  19361. else tail_append(new_param_glue(g1))
  19362. @ @<Append the display and perhaps also the equation number@>=
  19363. if e<>0 then
  19364.   begin r:=new_kern(z-w-e-d);
  19365.   if l then
  19366.     begin link(a):=r; link(r):=b; b:=a; d:=0;
  19367.     end
  19368.   else  begin link(b):=r; link(r):=a;
  19369.     end;
  19370.   b:=hpack(b,natural);
  19371.   end;
  19372. shift_amount(b):=s+d; append_to_vlist(b)
  19373. @ @<Append the glue or equation number following the display@>=
  19374. if (a<>null)and(e=0)and not l then
  19375.   begin tail_append(new_penalty(inf_penalty));
  19376.   shift_amount(a):=s+z-width(a);
  19377.   append_to_vlist(a);
  19378.   g2:=0;
  19379.   end;
  19380. if t<>adjust_head then {migrating material comes after equation number}
  19381.   begin link(tail):=link(adjust_head); tail:=t;
  19382.   end;
  19383. tail_append(new_penalty(post_display_penalty));
  19384. if g2>0 then tail_append(new_param_glue(g2))
  19385. @ When \.{\\halign} appears in a display, the alignment routines operate
  19386. essentially as they do in vertical mode. Then the following program is
  19387. activated, with |p| and |q| pointing to the beginning and end of the
  19388. resulting list, and with |aux_save| holding the |prev_depth| value.
  19389. @<Finish an alignment in a display@>=
  19390. begin do_assignments;
  19391. if cur_cmd<>math_shift then @<Pontificate about improper alignment in display@>
  19392. else @<Check that another \.\$ follows@>;
  19393. pop_nest;
  19394. tail_append(new_penalty(pre_display_penalty));
  19395. tail_append(new_param_glue(above_display_skip_code));
  19396. link(tail):=p;
  19397. if p<>null then tail:=q;
  19398. tail_append(new_penalty(post_display_penalty));
  19399. tail_append(new_param_glue(below_display_skip_code));
  19400. prev_depth:=aux_save.sc; resume_after_display;
  19401. @ @<Pontificate...@>=
  19402. begin print_err("Missing $$ inserted");
  19403. @.Missing {\$\$} inserted@>
  19404. help2("Displays can use special alignments (like \eqalignno)")@/
  19405.   ("only if nothing but the alignment itself is between $$'s.");
  19406. back_error;
  19407. @* \[49] Mode-independent processing.
  19408. The long |main_control| procedure has now been fully specified, except for
  19409. certain activities that are independent of the current mode. These activities
  19410. do not change the current vlist or hlist or mlist; if they change anything,
  19411. it is the value of a parameter or the meaning of a control sequence.
  19412. Assignments to values in |eqtb| can be global or local. Furthermore, a
  19413. control sequence can be defined to be `\.{\\long}' or `\.{\\outer}', and
  19414. it might or might not be expanded. The prefixes `\.{\\global}', `\.{\\long}',
  19415. and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
  19416. codes, making it possible to accumulate the union of all specified prefixes
  19417. by adding the corresponding codes.  (\PASCAL's |set| operations could also
  19418. have been used.)
  19419. @<Put each...@>=
  19420. primitive("long",prefix,1);
  19421. @!@:long_}{\.{\\long} primitive@>
  19422. primitive("outer",prefix,2);
  19423. @!@:outer_}{\.{\\outer} primitive@>
  19424. primitive("global",prefix,4);
  19425. @!@:global_}{\.{\\global} primitive@>
  19426. primitive("def",def,0);
  19427. @!@:def_}{\.{\\def} primitive@>
  19428. primitive("gdef",def,1);
  19429. @!@:gdef_}{\.{\\gdef} primitive@>
  19430. primitive("edef",def,2);
  19431. @!@:edef_}{\.{\\edef} primitive@>
  19432. primitive("xdef",def,3);
  19433. @!@:xdef_}{\.{\\xdef} primitive@>
  19434. @ @<Cases of |print_cmd_chr|...@>=
  19435. prefix: if chr_code=1 then print_esc("long")
  19436.   else if chr_code=2 then print_esc("outer")
  19437.   else print_esc("global");
  19438. def: if chr_code=0 then print_esc("def")
  19439.   else if chr_code=1 then print_esc("gdef")
  19440.   else if chr_code=2 then print_esc("edef")
  19441.   else print_esc("xdef");
  19442. @ Every prefix, and every command code that might or might not be prefixed,
  19443. calls the action procedure |prefixed_command|. This routine accumulates
  19444. a sequence of prefixes until coming to a non-prefix, then it carries out
  19445. the command.
  19446. @<Cases of |main_control| that don't...@>=
  19447. any_mode(toks_register),
  19448. any_mode(assign_toks),
  19449. any_mode(assign_int),
  19450. any_mode(assign_dimen),
  19451. any_mode(assign_glue),
  19452. any_mode(assign_mu_glue),
  19453. any_mode(assign_font_dimen),
  19454. any_mode(assign_font_int),
  19455. any_mode(set_aux),
  19456. any_mode(set_prev_graf),
  19457. any_mode(set_page_dimen),
  19458. any_mode(set_page_int),
  19459. any_mode(set_box_dimen),
  19460. any_mode(set_shape),
  19461. any_mode(def_code),
  19462. any_mode(def_family),
  19463. any_mode(set_font),
  19464. any_mode(def_font),
  19465. any_mode(register),
  19466. any_mode(advance),
  19467. any_mode(multiply),
  19468. any_mode(divide),
  19469. any_mode(prefix),
  19470. any_mode(let),
  19471. any_mode(shorthand_def),
  19472. any_mode(read_to_cs),
  19473. any_mode(def),
  19474. any_mode(set_box),
  19475. any_mode(hyph_data),
  19476. any_mode(set_interaction):prefixed_command;
  19477. @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
  19478. silently accepted.
  19479. @<Declare act...@>=
  19480. @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
  19481. procedure prefixed_command;
  19482. label done,exit;
  19483. var a:small_number; {accumulated prefix codes so far}
  19484. @!f:internal_font_number; {identifies a font}
  19485. @!j:halfword; {index into a \.{\\parshape} specification}
  19486. @!k:font_index; {index into |font_info|}
  19487. @!p,@!q:pointer; {for temporary short-term use}
  19488. @!n:integer; {ditto}
  19489. @!e:boolean; {should a definition be expanded? or was \.{\\let} not done?}
  19490. begin a:=0;
  19491. while cur_cmd=prefix do
  19492.   begin if not odd(a div cur_chr) then a:=a+cur_chr;
  19493.   @<Get the next non-blank non-relax...@>;
  19494.   if cur_cmd<=max_non_prefixed_command then
  19495.     @<Discard erroneous prefixes and |return|@>;
  19496.   end;
  19497. @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
  19498. @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
  19499. case cur_cmd of
  19500. @t\4@>@<Assignments@>@;
  19501. othercases confusion("prefix")
  19502. @:this can't happen prefix}{\quad prefix@>
  19503. endcases;
  19504. done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
  19505. exit:end;
  19506. @ @<Discard erroneous...@>=
  19507. begin print_err("You can't use a prefix with `");
  19508. @.You can't use a prefix with x@>
  19509. print_cmd_chr(cur_cmd,cur_chr); print_char("'");
  19510. help1("I'll pretend you didn't say \long or \outer or \global.");
  19511. back_error; return;
  19512. @ @<Discard the prefixes...@>=
  19513. if (cur_cmd<>def)and(a mod 4<>0) then
  19514.   begin print_err("You can't use `"); print_esc("long"); print("' or `");
  19515.   print_esc("outer"); print("' with `");
  19516. @.You can't use \\long...@>
  19517.   print_cmd_chr(cur_cmd,cur_chr); print_char("'");
  19518.   help1("I'll pretend you didn't say \long or \outer here.");
  19519.   error;
  19520.   end
  19521. @ The previous routine does not have to adjust |a| so that |a mod 4=0|,
  19522. since the following routines test for the \.{\\global} prefix as follows.
  19523. @d global==(a>=4)
  19524. @d define(#)==if global then geq_define(#)@+else eq_define(#)
  19525. @d word_define(#)==if global then geq_word_define(#)@+else eq_word_define(#)
  19526. @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
  19527. if global_defs<>0 then
  19528.   if global_defs<0 then
  19529.     begin if global then a:=a-4;
  19530.     end
  19531.   else  begin if not global then a:=a+4;
  19532.     end
  19533. @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
  19534. something similar, the |get_r_token| routine will substitute a special
  19535. control sequence for a token that is not redefinable.
  19536. @<Declare subprocedures for |prefixed_command|@>=
  19537. procedure get_r_token;
  19538. label restart;
  19539. begin restart: repeat get_token;
  19540. until cur_tok<>space_token;
  19541. if (cur_cs=0)or(cur_cs>frozen_control_sequence) then
  19542.   begin print_err("Missing control sequence inserted");
  19543. @.Missing control...@>
  19544.   help5("Please don't say `\def cs{...}', say `\def\cs{...}'.")@/
  19545.   ("I've inserted an inaccessible control sequence so that your")@/
  19546.   ("definition will be completed without mixing me up too badly.")@/
  19547.   ("You can recover graciously from this error, if you're")@/
  19548.   ("careful; see exercise 27.2 in The TeXbook.");
  19549. @:TeXbook}{\sl The \TeX book@>
  19550.   if cur_cs=0 then back_input;
  19551.   cur_tok:=cs_token_flag+frozen_protection; ins_error; goto restart;
  19552.   end;
  19553. @ @<Initialize table entries...@>=
  19554. text(frozen_protection):="inaccessible";
  19555. @ Here's an example of the way many of the following routines operate.
  19556. (Unfortunately, they aren't all as simple as this.)
  19557. @<Assignments@>=
  19558. set_font: define(cur_font_loc,data,cur_chr);
  19559. @ When a |def| command has been scanned,
  19560. |cur_chr| is odd if the definition is supposed to be global, and
  19561. |cur_chr>=2| if the definition is supposed to be expanded.
  19562. @<Assignments@>=
  19563. def: begin if odd(cur_chr)and not global and(global_defs>=0) then a:=a+4;
  19564.   e:=(cur_chr>=2); get_r_token; p:=cur_cs;
  19565.   q:=scan_toks(true,e); define(p,call+(a mod 4),def_ref);
  19566.   end;
  19567. @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
  19568. @<Put each...@>=
  19569. primitive("let",let,normal);@/
  19570. @!@:let_}{\.{\\let} primitive@>
  19571. primitive("futurelet",let,normal+1);@/
  19572. @!@:future_let_}{\.{\\futurelet} primitive@>
  19573. @ @<Cases of |print_cmd_chr|...@>=
  19574. let: if chr_code<>normal then print_esc("futurelet")@+else print_esc("let");
  19575. @ @<Assignments@>=
  19576. let:  begin n:=cur_chr;
  19577.   get_r_token; p:=cur_cs;
  19578.   if n=normal then
  19579.     begin repeat get_token;
  19580.     until cur_cmd<>spacer;
  19581.     if cur_tok=other_token+"=" then
  19582.       begin get_token;
  19583.       if cur_cmd=spacer then get_token;
  19584.       end;
  19585.     end
  19586.   else  begin get_token; q:=cur_tok; get_token; back_input;
  19587.     cur_tok:=q; back_input; {look ahead, then back up}
  19588.     end; {note that |back_input| doesn't affect |cur_cmd|, |cur_chr|}
  19589.   if cur_cmd>=call then add_token_ref(cur_chr);
  19590.   define(p,cur_cmd,cur_chr);
  19591.   end;
  19592. @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
  19593. a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
  19594. and the corresponding |chr| is the character code or math code. A \.{\\countdef}
  19595. or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
  19596. sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
  19597. corresponding |chr| is the |eqtb| location of the internal register in question.
  19598. @d char_def_code=0 {|shorthand_def| for \.{\\chardef}}
  19599. @d math_char_def_code=1 {|shorthand_def| for \.{\\mathchardef}}
  19600. @d count_def_code=2 {|shorthand_def| for \.{\\countdef}}
  19601. @d dimen_def_code=3 {|shorthand_def| for \.{\\dimendef}}
  19602. @d skip_def_code=4 {|shorthand_def| for \.{\\skipdef}}
  19603. @d mu_skip_def_code=5 {|shorthand_def| for \.{\\muskipdef}}
  19604. @d toks_def_code=6 {|shorthand_def| for \.{\\toksdef}}
  19605. @<Put each...@>=
  19606. primitive("chardef",shorthand_def,char_def_code);@/
  19607. @!@:char_def_}{\.{\\chardef} primitive@>
  19608. primitive("mathchardef",shorthand_def,math_char_def_code);@/
  19609. @!@:math_char_def_}{\.{\\mathchardef} primitive@>
  19610. primitive("countdef",shorthand_def,count_def_code);@/
  19611. @!@:count_def_}{\.{\\countdef} primitive@>
  19612. primitive("dimendef",shorthand_def,dimen_def_code);@/
  19613. @!@:dimen_def_}{\.{\\dimendef} primitive@>
  19614. primitive("skipdef",shorthand_def,skip_def_code);@/
  19615. @!@:skip_def_}{\.{\\skipdef} primitive@>
  19616. primitive("muskipdef",shorthand_def,mu_skip_def_code);@/
  19617. @!@:mu_skip_def_}{\.{\\muskipdef} primitive@>
  19618. primitive("toksdef",shorthand_def,toks_def_code);@/
  19619. @!@:toks_def_}{\.{\\toksdef} primitive@>
  19620. @ @<Cases of |print_cmd_chr|...@>=
  19621. shorthand_def: case chr_code of
  19622.   char_def_code: print_esc("chardef");
  19623.   math_char_def_code: print_esc("mathchardef");
  19624.   count_def_code: print_esc("countdef");
  19625.   dimen_def_code: print_esc("dimendef");
  19626.   skip_def_code: print_esc("skipdef");
  19627.   mu_skip_def_code: print_esc("muskipdef");
  19628.   othercases print_esc("toksdef")
  19629.   endcases;
  19630. char_given: begin print_esc("char"); print_hex(chr_code);
  19631.   end;
  19632. math_given: begin print_esc("mathchar"); print_hex(chr_code);
  19633.   end;
  19634. @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
  19635. while scanning the definition will simply stop the scanning instead of
  19636. producing an ``undefined control sequence'' error or expanding the
  19637. previous meaning.  This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
  19638. @<Assignments@>=
  19639. shorthand_def: begin n:=cur_chr; get_r_token; p:=cur_cs; define(p,relax,256);
  19640.   scan_optional_equals;
  19641.   case n of
  19642.   char_def_code: begin scan_char_num; define(p,char_given,cur_val);
  19643.     end;
  19644.   math_char_def_code: begin scan_fifteen_bit_int; define(p,math_given,cur_val);
  19645.     end;
  19646.   othercases begin scan_eight_bit_int;
  19647.     case n of
  19648.     count_def_code: define(p,assign_int,count_base+cur_val);
  19649.     dimen_def_code: define(p,assign_dimen,scaled_base+cur_val);
  19650.     skip_def_code: define(p,assign_glue,skip_base+cur_val);
  19651.     mu_skip_def_code: define(p,assign_mu_glue,mu_skip_base+cur_val);
  19652.     toks_def_code: define(p,assign_toks,toks_base+cur_val);
  19653.     end; {there are no other cases}
  19654.     end
  19655.   endcases;
  19656.   end;
  19657. @ @<Assignments@>=
  19658. read_to_cs: begin scan_int; n:=cur_val;
  19659.   if not scan_keyword("to") then
  19660.     begin print_err("Missing `to' inserted");
  19661. @.Missing `to'...@>
  19662.     help2("You should have said `\read<number> to \cs'.")@/
  19663.     ("I'm going to look for the \cs now."); error;
  19664.     end;
  19665.   get_r_token;
  19666.   p:=cur_cs; read_toks(n,p); define(p,call,cur_val);
  19667.   end;
  19668. @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
  19669. their values in the following way. (For safety's sake, we place an
  19670. enclosing pair of braces around an \.{\\output} list.)
  19671. @<Assignments@>=
  19672. toks_register,assign_toks: begin q:=cur_cs;
  19673.   if cur_cmd=toks_register then
  19674.     begin scan_eight_bit_int; p:=toks_base+cur_val;
  19675.     end
  19676.   else p:=cur_chr; {|p=every_par_loc| or |output_routine_loc| or \dots}
  19677.   scan_optional_equals;
  19678.   @<Get the next non-blank non-relax non-call token@>;
  19679.   if cur_cmd<>left_brace then @<If the right-hand side is a token parameter
  19680.       or token register, finish the assignment and |goto done|@>;
  19681.   back_input; cur_cs:=q; q:=scan_toks(false,false);
  19682.   if link(def_ref)=null then {empty list: revert to the default}
  19683.     begin define(p,undefined_cs,null); free_avail(def_ref);
  19684.     end
  19685.   else  begin if p=output_routine_loc then {enclose in curlies}
  19686.       begin link(q):=get_avail; q:=link(q);
  19687.       info(q):=right_brace_token+"}";
  19688.       q:=get_avail; info(q):=left_brace_token+"{";
  19689.       link(q):=link(def_ref); link(def_ref):=q;
  19690.       end;
  19691.     define(p,call,def_ref);
  19692.     end;
  19693.   end;
  19694. @ @<If the right-hand side is a token parameter...@>=
  19695. begin if cur_cmd=toks_register then
  19696.   begin scan_eight_bit_int; cur_cmd:=assign_toks; cur_chr:=toks_base+cur_val;
  19697.   end;
  19698. if cur_cmd=assign_toks then
  19699.   begin q:=equiv(cur_chr);
  19700.   if q=null then define(p,undefined_cs,null)
  19701.   else  begin add_token_ref(q); define(p,call,q);
  19702.     end;
  19703.   goto done;
  19704.   end;
  19705. @ Similar routines are used to assign values to the numeric parameters.
  19706. @<Assignments@>=
  19707. assign_int: begin p:=cur_chr; scan_optional_equals; scan_int;
  19708.   word_define(p,cur_val);
  19709.   end;
  19710. assign_dimen: begin p:=cur_chr; scan_optional_equals;
  19711.   scan_normal_dimen; word_define(p,cur_val);
  19712.   end;
  19713. assign_glue,assign_mu_glue: begin p:=cur_chr; n:=cur_cmd; scan_optional_equals;
  19714.   if n=assign_mu_glue then scan_glue(mu_val)@+else scan_glue(glue_val);
  19715.   trap_zero_glue;
  19716.   define(p,glue_ref,cur_val);
  19717.   end;
  19718. @ When a glue register or parameter becomes zero, it will always point to
  19719. |zero_glue| because of the following procedure. (Exception: The tabskip
  19720. glue isn't trapped while preambles are being scanned.)
  19721. @<Declare subprocedures for |prefixed_command|@>=
  19722. procedure trap_zero_glue;
  19723. begin if (width(cur_val)=0)and(stretch(cur_val)=0)and(shrink(cur_val)=0) then
  19724.   begin add_glue_ref(zero_glue);
  19725.   delete_glue_ref(cur_val); cur_val:=zero_glue;
  19726.   end;
  19727. @ The various character code tables are changed by the |def_code| commands,
  19728. and the font families are declared by |def_family|.
  19729. @<Put each...@>=
  19730. primitive("catcode",def_code,cat_code_base);
  19731. @!@:cat_code_}{\.{\\catcode} primitive@>
  19732. primitive("mathcode",def_code,math_code_base);
  19733. @!@:math_code_}{\.{\\mathcode} primitive@>
  19734. primitive("lccode",def_code,lc_code_base);
  19735. @!@:lc_code_}{\.{\\lccode} primitive@>
  19736. primitive("uccode",def_code,uc_code_base);
  19737. @!@:uc_code_}{\.{\\uccode} primitive@>
  19738. primitive("sfcode",def_code,sf_code_base);
  19739. @!@:sf_code_}{\.{\\sfcode} primitive@>
  19740. primitive("delcode",def_code,del_code_base);
  19741. @!@:del_code_}{\.{\\delcode} primitive@>
  19742. primitive("textfont",def_family,math_font_base);
  19743. @!@:text_font_}{\.{\\textfont} primitive@>
  19744. primitive("scriptfont",def_family,math_font_base+script_size);
  19745. @!@:script_font_}{\.{\\scriptfont} primitive@>
  19746. primitive("scriptscriptfont",def_family,math_font_base+script_script_size);
  19747. @!@:script_script_font_}{\.{\\scriptscriptfont} primitive@>
  19748. @ @<Cases of |print_cmd_chr|...@>=
  19749. def_code: if chr_code=cat_code_base then print_esc("catcode")
  19750.   else if chr_code=math_code_base then print_esc("mathcode")
  19751.   else if chr_code=lc_code_base then print_esc("lccode")
  19752.   else if chr_code=uc_code_base then print_esc("uccode")
  19753.   else if chr_code=sf_code_base then print_esc("sfcode")
  19754.   else print_esc("delcode");
  19755. def_family: print_size(chr_code-math_font_base);
  19756. @ The different types of code values have different legal ranges; the
  19757. following program is careful to check each case properly.
  19758. @<Assignments@>=
  19759. def_code: begin @<Let |n| be the largest legal code value, based on |cur_chr|@>;
  19760.   p:=cur_chr; scan_char_num; p:=p+cur_val; scan_optional_equals;
  19761.   scan_int;
  19762.   if ((cur_val<0)and(p<del_code_base))or(cur_val>n) then
  19763.     begin print_err("Invalid code ("); print_int(cur_val);
  19764. @.Invalid code@>
  19765.     if p<del_code_base then print("), should be in the range 0..")
  19766.     else print("), should be at most ");
  19767.     print_int(n);
  19768.     help1("I'm going to use 0 instead of that illegal code value.");@/
  19769.     error; cur_val:=0;
  19770.     end;
  19771.   if p<math_code_base then define(p,data,cur_val)
  19772.   else if p<del_code_base then define(p,data,hi(cur_val))
  19773.   else word_define(p,cur_val);
  19774.   end;
  19775. @ @<Let |n| be the largest...@>=
  19776. if cur_chr=cat_code_base then n:=max_char_code
  19777. else if cur_chr=math_code_base then n:=@'100000
  19778. else if cur_chr=sf_code_base then n:=@'77777
  19779. else if cur_chr=del_code_base then n:=@'77777777
  19780. else n:=255
  19781. @ @<Assignments@>=
  19782. def_family: begin p:=cur_chr; scan_four_bit_int; p:=p+cur_val;
  19783.   scan_optional_equals; scan_font_ident; define(p,data,cur_val);
  19784.   end;
  19785. @ Next we consider changes to \TeX's numeric registers.
  19786. @<Assignments@>=
  19787. register,advance,multiply,divide: do_register_command(a);
  19788. @ We use the fact that |register<advance<multiply<divide|.
  19789. @<Declare subprocedures for |prefixed_command|@>=
  19790. procedure do_register_command(@!a:small_number);
  19791. label found,exit;
  19792. var l,@!q,@!r,@!s:pointer; {for list manipulation}
  19793. @!p:int_val..mu_val; {type of register involved}
  19794. begin q:=cur_cmd;
  19795. @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
  19796. if q=register then scan_optional_equals
  19797. else if scan_keyword("by") then do_nothing; {optional `\.{by}'}
  19798. arith_error:=false;
  19799. if q<multiply then @<Compute result of |register| or
  19800.     |advance|, put it in |cur_val|@>
  19801. else @<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
  19802. if arith_error then
  19803.   begin print_err("Arithmetic overflow");
  19804. @.Arithmetic overflow@>
  19805.   help2("I can't carry out that multiplication or division,")@/
  19806.     ("since the result is out of range.");
  19807.   error; return;
  19808.   end;
  19809. if p<glue_val then word_define(l,cur_val)
  19810. else  begin trap_zero_glue; define(l,glue_ref,cur_val);
  19811.   end;
  19812. exit: end;
  19813. @ Here we use the fact that the consecutive codes |int_val...mu_val| and
  19814. |assign_int..assign_mu_glue| correspond to each other nicely.
  19815. @<Compute the register location |l| and its type |p|...@>=
  19816. begin if q<>register then
  19817.   begin get_x_token;
  19818.   if (cur_cmd>=assign_int)and(cur_cmd<=assign_mu_glue) then
  19819.     begin l:=cur_chr; p:=cur_cmd-assign_int; goto found;
  19820.     end;
  19821.   if cur_cmd<>register then
  19822.     begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
  19823. @.You can't use x after ...@>
  19824.     print("' after "); print_cmd_chr(q,0);
  19825.     help1("I'm forgetting what you said and not changing anything.");
  19826.     error; return;
  19827.     end;
  19828.   end;
  19829. p:=cur_chr; scan_eight_bit_int;
  19830. case p of
  19831. int_val: l:=cur_val+count_base;
  19832. dimen_val: l:=cur_val+scaled_base;
  19833. glue_val: l:=cur_val+skip_base;
  19834. mu_val: l:=cur_val+mu_skip_base;
  19835. end; {there are no other cases}
  19836. found:
  19837. @ @<Compute result of |register| or |advance|...@>=
  19838. if p<glue_val then
  19839.   begin if p=int_val then scan_int@+else scan_normal_dimen;
  19840.   if q=advance then cur_val:=cur_val+eqtb[l].int;
  19841.   end
  19842. else  begin scan_glue(p);
  19843.   if q=advance then @<Compute the sum of two glue specs@>;
  19844.   end
  19845. @ @<Compute the sum of two glue specs@>=
  19846. begin q:=new_spec(cur_val); r:=equiv(l);
  19847. delete_glue_ref(cur_val);
  19848. width(q):=width(q)+width(r);
  19849. if stretch(q)=0 then stretch_order(q):=normal;
  19850. if stretch_order(q)=stretch_order(r) then stretch(q):=stretch(q)+stretch(r)
  19851. else if (stretch_order(q)<stretch_order(r))and(stretch(r)<>0) then
  19852.   begin stretch(q):=stretch(r); stretch_order(q):=stretch_order(r);
  19853.   end;
  19854. if shrink(q)=0 then shrink_order(q):=normal;
  19855. if shrink_order(q)=shrink_order(r) then shrink(q):=shrink(q)+shrink(r)
  19856. else if (shrink_order(q)<shrink_order(r))and(shrink(r)<>0) then
  19857.   begin shrink(q):=shrink(r); shrink_order(q):=shrink_order(r);
  19858.   end;
  19859. cur_val:=q;
  19860. @ @<Compute result of |multiply| or |divide|...@>=
  19861. begin scan_int;
  19862. if p<glue_val then
  19863.   if q=multiply then
  19864.     if p=int_val then cur_val:=mult_integers(eqtb[l].int,cur_val)
  19865.     else cur_val:=nx_plus_y(eqtb[l].int,cur_val,0)
  19866.   else cur_val:=x_over_n(eqtb[l].int,cur_val)
  19867. else  begin s:=equiv(l); r:=new_spec(s);
  19868.   if q=multiply then
  19869.     begin width(r):=nx_plus_y(width(s),cur_val,0);
  19870.     stretch(r):=nx_plus_y(stretch(s),cur_val,0);
  19871.     shrink(r):=nx_plus_y(shrink(s),cur_val,0);
  19872.     end
  19873.   else  begin width(r):=x_over_n(width(s),cur_val);
  19874.     stretch(r):=x_over_n(stretch(s),cur_val);
  19875.     shrink(r):=x_over_n(shrink(s),cur_val);
  19876.     end;
  19877.   cur_val:=r;
  19878.   end;
  19879. @ The processing of boxes is somewhat different, because we may need
  19880. to scan and create an entire box before we actually change the value of the old
  19881. @<Assignments@>=
  19882. set_box: begin scan_eight_bit_int;
  19883.   if global then n:=256+cur_val@+else n:=cur_val;
  19884.   scan_optional_equals;
  19885.   if set_box_allowed then scan_box(box_flag+n)
  19886.   else begin print_err("Improper "); print_esc("setbox");
  19887. @.Improper \\setbox@>
  19888.     help2("Sorry, \setbox is not allowed after \halign in a display,")@/
  19889.     ("or between \accent and an accented character."); error;
  19890.     end;
  19891.   end;
  19892. @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
  19893. command is sensed. Similarly, |prev_graf| is changed in the presence of
  19894. |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
  19895. |set_page_int|. These definitions are always global.
  19896. When some dimension of a box register is changed, the change isn't exactly
  19897. global; but \TeX\ does not look at the \.{\\global} switch.
  19898. @<Assignments@>=
  19899. set_aux:alter_aux;
  19900. set_prev_graf:alter_prev_graf;
  19901. set_page_dimen:alter_page_so_far;
  19902. set_page_int:alter_integer;
  19903. set_box_dimen:alter_box_dimen;
  19904. @ @<Declare subprocedures for |prefixed_command|@>=
  19905. procedure alter_aux;
  19906. var c:halfword; {|hmode| or |vmode|}
  19907. begin if cur_chr<>abs(mode) then report_illegal_case
  19908. else  begin c:=cur_chr; scan_optional_equals;
  19909.   if c=vmode then
  19910.     begin scan_normal_dimen; prev_depth:=cur_val;
  19911.     end
  19912.   else  begin scan_int;
  19913.     if (cur_val<=0)or(cur_val>32767) then
  19914.       begin print_err("Bad space factor");
  19915. @.Bad space factor@>
  19916.       help1("I allow only values in the range 1..32767 here.");
  19917.       int_error(cur_val);
  19918.       end
  19919.     else space_factor:=cur_val;
  19920.     end;
  19921.   end;
  19922. @ @<Declare subprocedures for |prefixed_command|@>=
  19923. procedure alter_prev_graf;
  19924. var p:0..nest_size; {index into |nest|}
  19925. begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
  19926. while abs(nest[p].mode_field)<>vmode do decr(p);
  19927. scan_optional_equals; scan_int;
  19928. if cur_val<0 then
  19929.   begin print_err("Bad "); print_esc("prevgraf");
  19930. @.Bad \\prevgraf@>
  19931.   help1("I allow only nonnegative values here.");
  19932.   int_error(cur_val);
  19933.   end
  19934. else  begin nest[p].pg_field:=cur_val; cur_list:=nest[nest_ptr];
  19935.   end;
  19936. @ @<Declare subprocedures for |prefixed_command|@>=
  19937. procedure alter_page_so_far;
  19938. var c:0..7; {index into |page_so_far|}
  19939. begin c:=cur_chr; scan_optional_equals; scan_normal_dimen;
  19940. page_so_far[c]:=cur_val;
  19941. @ @<Declare subprocedures for |prefixed_command|@>=
  19942. procedure alter_integer;
  19943. var c:0..1; {0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}}
  19944. begin c:=cur_chr; scan_optional_equals; scan_int;
  19945. if c=0 then dead_cycles:=cur_val
  19946. else insert_penalties:=cur_val;
  19947. @ @<Declare subprocedures for |prefixed_command|@>=
  19948. procedure alter_box_dimen;
  19949. var c:small_number; {|width_offset| or |height_offset| or |depth_offset|}
  19950. @!b:eight_bits; {box number}
  19951. begin c:=cur_chr; scan_eight_bit_int; b:=cur_val; scan_optional_equals;
  19952. scan_normal_dimen;
  19953. if box(b)<>null then mem[box(b)+c].sc:=cur_val;
  19954. @ Paragraph shapes are set up in the obvious way.
  19955. @<Assignments@>=
  19956. set_shape: begin scan_optional_equals; scan_int; n:=cur_val;
  19957.   if n<=0 then p:=null
  19958.   else  begin p:=get_node(2*n+1); info(p):=n;
  19959.     for j:=1 to n do
  19960.       begin scan_normal_dimen;
  19961.       mem[p+2*j-1].sc:=cur_val; {indentation}
  19962.       scan_normal_dimen;
  19963.       mem[p+2*j].sc:=cur_val; {width}
  19964.       end;
  19965.     end;
  19966.   define(par_shape_loc,shape_ref,p);
  19967.   end;
  19968. @ Here's something that isn't quite so obvious. It guarantees that
  19969. |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
  19970. doesn't overflow the memory capacity.
  19971. @<Check the ``constant''...@>=
  19972. if 2*max_halfword<mem_top-mem_min then bad:=41;
  19973. @ New hyphenation data is loaded by the |hyph_data| command.
  19974. @<Put each...@>=
  19975. primitive("hyphenation",hyph_data,0);
  19976. @!@:hyphenation_}{\.{\\hyphenation} primitive@>
  19977. primitive("patterns",hyph_data,1);
  19978. @!@:patterns_}{\.{\\patterns} primitive@>
  19979. @ @<Cases of |print_cmd_chr|...@>=
  19980. hyph_data: if chr_code=1 then print_esc("patterns")
  19981.   else print_esc("hyphenation");
  19982. @ @<Assignments@>=
  19983. hyph_data: if cur_chr=1 then
  19984.     begin @!init new_patterns; goto done;@;@+tini@/
  19985.     print_err("Patterns can be loaded only by INITEX");
  19986. @.Patterns can be...@>
  19987.     help0; error;
  19988.     repeat get_token; until cur_cmd=right_brace; {flush the patterns}
  19989.     return;
  19990.     end
  19991.   else  begin new_hyph_exceptions; goto done;
  19992.     end;
  19993. @ All of \TeX's parameters are kept in |eqtb| except the font information,
  19994. the interaction mode, and the hyphenation tables; these are strictly global.
  19995. @<Assignments@>=
  19996. assign_font_dimen: begin find_font_dimen(true); k:=cur_val;
  19997.   scan_optional_equals; scan_normal_dimen; font_info[k].sc:=cur_val;
  19998.   end;
  19999. assign_font_int: begin n:=cur_chr; scan_font_ident; f:=cur_val;
  20000.   scan_optional_equals; scan_int;
  20001.   if n=0 then hyphen_char[f]:=cur_val@+else skew_char[f]:=cur_val;
  20002.   end;
  20003. @ @<Put each...@>=
  20004. primitive("hyphenchar",assign_font_int,0);
  20005. @!@:hyphen_char_}{\.{\\hyphenchar} primitive@>
  20006. primitive("skewchar",assign_font_int,1);
  20007. @!@:skew_char_}{\.{\\skewchar} primitive@>
  20008. @ @<Cases of |print_cmd_chr|...@>=
  20009. assign_font_int: if chr_code=0 then print_esc("hyphenchar")
  20010.   else print_esc("skewchar");
  20011. @ Here is where the information for a new font gets loaded.
  20012. @<Assignments@>=
  20013. def_font: new_font(a);
  20014. @ @<Declare subprocedures for |prefixed_command|@>=
  20015. procedure new_font(@!a:small_number);
  20016. label common_ending;
  20017. var u:pointer; {user's font identifier}
  20018. @!s:scaled; {stated ``at'' size, or negative of scaled magnification}
  20019. @!f:internal_font_number; {runs through existing fonts}
  20020. @!t:str_number; {name for the frozen font identifier}
  20021. @!old_setting:0..max_selector; {holds |selector| setting}
  20022. @!flushable_string:str_number; {string not yet referenced}
  20023. begin if job_name=0 then open_log_file;
  20024.   {avoid confusing \.{texput} with the font name}
  20025. @.texput@>
  20026. get_r_token; u:=cur_cs;
  20027. if u>=hash_base then t:=text(u)
  20028. else if u>=single_base then
  20029.   if u=null_cs then t:="FONT"@+else t:=u-single_base
  20030. else  begin old_setting:=selector; selector:=new_string;
  20031.   print("FONT"); print(u-active_base); selector:=old_setting;
  20032. @.FONTx@>
  20033.   str_room(1); t:=make_string;
  20034.   end;
  20035. define(u,set_font,null_font); scan_optional_equals; scan_file_name;
  20036. @<Scan the font size specification@>;
  20037. @<If this font has already been loaded, set |f| to the internal
  20038.   font number and |goto common_ending|@>;
  20039. f:=read_font_info(u,cur_name,cur_area,s);
  20040. common_ending: equiv(u):=f; eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
  20041. @ @<Scan the font size specification@>=
  20042. name_in_progress:=true; {this keeps |cur_name| from being changed}
  20043. if scan_keyword("at") then @<Put the \(p)(positive) `at' size into |s|@>
  20044. @.at@>
  20045. else if scan_keyword("scaled") then
  20046. @.scaled@>
  20047.   begin scan_int; s:=-cur_val;
  20048.   if (cur_val<=0)or(cur_val>32768) then
  20049.     begin print_err("Illegal magnification has been changed to 1000");@/
  20050. @.Illegal magnification...@>
  20051.     help1("The magnification ratio must be between 1 and 32768.");
  20052.     int_error(cur_val); s:=-1000;
  20053.     end;
  20054.   end
  20055. else s:=-1000;
  20056. name_in_progress:=false
  20057. @ @<Put the \(p)(positive) `at' size into |s|@>=
  20058. begin scan_normal_dimen; s:=cur_val;
  20059. if (s<=0)or(s>=@'1000000000) then
  20060.   begin print_err("Improper `at' size (");
  20061.   print_scaled(s); print("pt), replaced by 10pt");
  20062. @.Improper `at' size...@>
  20063.   help2("I can only handle fonts at positive sizes that are")@/
  20064.   ("less than 2048pt, so I've changed what you said to 10pt.");
  20065.   error; s:=10*unity;
  20066.   end;
  20067. @ When the user gives a new identifier to a font that was previously loaded,
  20068. the new name becomes the font identifier of record. Font names `\.{xyz}' and
  20069. `\.{XYZ}' are considered to be different.
  20070. @<If this font has already been loaded...@>=
  20071. flushable_string:=str_ptr-1;
  20072. for f:=font_base+1 to font_ptr do
  20073.   if str_eq_str(font_name[f],cur_name)and str_eq_str(font_area[f],cur_area) then
  20074.     begin if cur_name=flushable_string then
  20075.       begin flush_string; cur_name:=font_name[f];
  20076.       end;
  20077.     if s>0 then
  20078.       begin if s=font_size[f] then goto common_ending;
  20079.       end
  20080.     else if font_size[f]=xn_over_d(font_dsize[f],-s,1000) then
  20081.       goto common_ending;
  20082.     end
  20083. @ @<Cases of |print_cmd_chr|...@>=
  20084. set_font:begin print("select font "); slow_print(font_name[chr_code]);
  20085.   if font_size[chr_code]<>font_dsize[chr_code] then
  20086.     begin print(" at "); print_scaled(font_size[chr_code]);
  20087.     print("pt");
  20088.     end;
  20089.   end;
  20090. @ @<Put each...@>=
  20091. primitive("batchmode",set_interaction,batch_mode);
  20092. @!@:batch_mode_}{\.{\\batchmode} primitive@>
  20093. primitive("nonstopmode",set_interaction,nonstop_mode);
  20094. @!@:nonstop_mode_}{\.{\\nonstopmode} primitive@>
  20095. primitive("scrollmode",set_interaction,scroll_mode);
  20096. @!@:scroll_mode_}{\.{\\scrollmode} primitive@>
  20097. primitive("errorstopmode",set_interaction,error_stop_mode);
  20098. @!@:error_stop_mode_}{\.{\\errorstopmode} primitive@>
  20099. @ @<Cases of |print_cmd_chr|...@>=
  20100. set_interaction: case chr_code of
  20101.   batch_mode: print_esc("batchmode");
  20102.   nonstop_mode: print_esc("nonstopmode");
  20103.   scroll_mode: print_esc("scrollmode");
  20104.   othercases print_esc("errorstopmode")
  20105.   endcases;
  20106. @ @<Assignments@>=
  20107. set_interaction: new_interaction;
  20108. @ @<Declare subprocedures for |prefixed_command|@>=
  20109. procedure new_interaction;
  20110. begin print_ln;
  20111. interaction:=cur_chr;
  20112. @<Initialize the print |selector| based on |interaction|@>;
  20113. if log_opened then selector:=selector+2;
  20114. @ The \.{\\afterassignment} command puts a token into the global
  20115. variable |after_token|. This global variable is examined just after
  20116. every assignment has been performed.
  20117. @<Glob...@>=
  20118. @!after_token:halfword; {zero, or a saved token}
  20119. @ @<Set init...@>=
  20120. after_token:=0;
  20121. @ @<Cases of |main_control| that don't...@>=
  20122. any_mode(after_assignment):begin get_token; after_token:=cur_tok;
  20123.   end;
  20124. @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
  20125. if after_token<>0 then
  20126.   begin cur_tok:=after_token; back_input; after_token:=0;
  20127.   end
  20128. @ Here is a procedure that might be called `Get the next non-blank non-relax
  20129. non-call non-assignment token'.
  20130. @<Declare act...@>=
  20131. procedure do_assignments;
  20132. label exit;
  20133. begin loop begin @<Get the next non-blank non-relax...@>;
  20134.   if cur_cmd<=max_non_prefixed_command then return;
  20135.   set_box_allowed:=false; prefixed_command; set_box_allowed:=true;
  20136.   end;
  20137. exit:end;
  20138. @ @<Cases of |main_control| that don't...@>=
  20139. any_mode(after_group):begin get_token; save_for_after(cur_tok);
  20140.   end;
  20141. @ Files for \.{\\read} are opened and closed by the |in_stream| command.
  20142. @<Put each...@>=
  20143. primitive("openin",in_stream,1);
  20144. @!@:open_in_}{\.{\\openin} primitive@>
  20145. primitive("closein",in_stream,0);
  20146. @!@:close_in_}{\.{\\closein} primitive@>
  20147. @ @<Cases of |print_cmd_chr|...@>=
  20148. in_stream: if chr_code=0 then print_esc("closein")
  20149.   else print_esc("openin");
  20150. @ @<Cases of |main_control| that don't...@>=
  20151. any_mode(in_stream): open_or_close_in;
  20152. @ @<Declare act...@>=
  20153. procedure open_or_close_in;
  20154. var c:0..1; {1 for \.{\\openin}, 0 for \.{\\closein}}
  20155. @!n:0..15; {stream number}
  20156. begin c:=cur_chr; scan_four_bit_int; n:=cur_val;
  20157. if read_open[n]<>closed then
  20158.   begin a_close(read_file[n]); read_open[n]:=closed;
  20159.   end;
  20160. if c<>0 then
  20161.   begin scan_optional_equals; scan_file_name;
  20162.   if cur_ext="" then cur_ext:=".tex";
  20163.   pack_cur_name;
  20164.   if a_open_in(read_file[n]) then read_open[n]:=just_open;
  20165.   end;
  20166. @ The user can issue messages to the terminal, regardless of the
  20167. current mode.
  20168. @<Cases of |main_control| that don't...@>=
  20169. any_mode(message):issue_message;
  20170. @ @<Put each...@>=
  20171. primitive("message",message,0);
  20172. @!@:message_}{\.{\\message} primitive@>
  20173. primitive("errmessage",message,1);
  20174. @!@:err_message_}{\.{\\errmessage} primitive@>
  20175. @ @<Cases of |print_cmd_chr|...@>=
  20176. message: if chr_code=0 then print_esc("message")
  20177.   else print_esc("errmessage");
  20178. @ @<Declare act...@>=
  20179. procedure issue_message;
  20180. var old_setting:0..max_selector; {holds |selector| setting}
  20181. @!c:0..1; {identifies \.{\\message} and \.{\\errmessage}}
  20182. @!s:str_number; {the message}
  20183. begin c:=cur_chr; link(garbage):=scan_toks(false,true);
  20184. old_setting:=selector; selector:=new_string;
  20185. token_show(def_ref); selector:=old_setting;
  20186. flush_list(def_ref);
  20187. str_room(1); s:=make_string;
  20188. if c=0 then @<Print string |s| on the terminal@>
  20189. else @<Print string |s| as an error message@>;
  20190. flush_string;
  20191. @ @<Print string |s| on the terminal@>=
  20192. begin if term_offset+length(s)>max_print_line-2 then print_ln
  20193. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  20194. slow_print(s); update_terminal;
  20195. @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
  20196. \.{\\errhelp}, we don't want to give a long help message each time. So we
  20197. give a verbose explanation only once.
  20198. @<Glob...@>=
  20199. @!long_help_seen:boolean; {has the long \.{\\errmessage} help been used?}
  20200. @ @<Set init...@>=long_help_seen:=false;
  20201. @ @<Print string |s| as an error message@>=
  20202. begin print_err(""); slow_print(s);
  20203. if err_help<>null then use_err_help:=true
  20204. else if long_help_seen then help1("(That was another \errmessage.)")
  20205. else  begin if interaction<error_stop_mode then long_help_seen:=true;
  20206.   help4("This error message was generated by an \errmessage")@/
  20207.   ("command, so I can't give any explicit help.")@/
  20208.   ("Pretend that you're Hercule Poirot: Examine all clues,")@/
  20209. @^Poirot, Hercule@>
  20210.   ("and deduce the truth by order and method.");
  20211.   end;
  20212. error; use_err_help:=false;
  20213. @ The |error| routine calls on |give_err_help| if help is requested from
  20214. the |err_help| parameter.
  20215. @p procedure give_err_help;
  20216. begin token_show(err_help);
  20217. @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
  20218. building a token list and then changing the cases of the letters in it.
  20219. @<Cases of |main_control| that don't...@>=
  20220. any_mode(case_shift):shift_case;
  20221. @ @<Put each...@>=
  20222. primitive("lowercase",case_shift,lc_code_base);
  20223. @!@:lowercase_}{\.{\\lowercase} primitive@>
  20224. primitive("uppercase",case_shift,uc_code_base);
  20225. @!@:uppercase_}{\.{\\uppercase} primitive@>
  20226. @ @<Cases of |print_cmd_chr|...@>=
  20227. case_shift:if chr_code=lc_code_base then print_esc("lowercase")
  20228.   else print_esc("uppercase");
  20229. @ @<Declare act...@>=
  20230. procedure shift_case;
  20231. var b:pointer; {|lc_code_base| or |uc_code_base|}
  20232. @!p:pointer; {runs through the token list}
  20233. @!t:halfword; {token}
  20234. @!c:eight_bits; {character code}
  20235. begin b:=cur_chr; p:=scan_toks(false,false); p:=link(def_ref);
  20236. while p<>null do
  20237.   begin @<Change the case of the token in |p|, if a change is appropriate@>;
  20238.   p:=link(p);
  20239.   end;
  20240. back_list(link(def_ref)); free_avail(def_ref); {omit reference count}
  20241. @ When the case of a |chr_code| changes, we don't change the |cmd|.
  20242. We also change active characters, using the fact that
  20243. |cs_token_flag+active_base| is a multiple of~256.
  20244. @^data structure assumptions@>
  20245. @<Change the case of the token in |p|, if a change is appropriate@>=
  20246. t:=info(p);
  20247. if t<cs_token_flag+single_base then
  20248.   begin c:=t mod 256;
  20249.   if equiv(b+c)<>0 then info(p):=t-c+equiv(b+c);
  20250.   end
  20251. @ We come finally to the last pieces missing from |main_control|, namely the
  20252. `\.{\\show}' commands that are useful when debugging.
  20253. @<Cases of |main_control| that don't...@>=
  20254. any_mode(xray): show_whatever;
  20255. @ @d show_code=0 { \.{\\show} }
  20256. @d show_box_code=1 { \.{\\showbox} }
  20257. @d show_the_code=2 { \.{\\showthe} }
  20258. @d show_lists=3 { \.{\\showlists} }
  20259. @<Put each...@>=
  20260. primitive("show",xray,show_code);
  20261. @!@:show_}{\.{\\show} primitive@>
  20262. primitive("showbox",xray,show_box_code);
  20263. @!@:show_box_}{\.{\\showbox} primitive@>
  20264. primitive("showthe",xray,show_the_code);
  20265. @!@:show_the_}{\.{\\showthe} primitive@>
  20266. primitive("showlists",xray,show_lists);
  20267. @!@:show_lists_}{\.{\\showlists} primitive@>
  20268. @ @<Cases of |print_cmd_chr|...@>=
  20269. xray: case chr_code of
  20270.   show_box_code:print_esc("showbox");
  20271.   show_the_code:print_esc("showthe");
  20272.   show_lists:print_esc("showlists");
  20273.   othercases print_esc("show")
  20274.   endcases;
  20275. @ @<Declare act...@>=
  20276. procedure show_whatever;
  20277. label common_ending;
  20278. var p:pointer; {tail of a token list to show}
  20279. begin case cur_chr of
  20280. show_lists: begin begin_diagnostic; show_activities;
  20281.   end;
  20282. show_box_code: @<Show the current contents of a box@>;
  20283. show_code: @<Show the current meaning of a token, then |goto common_ending|@>;
  20284. othercases @<Show the current value of some parameter or register,
  20285.   then |goto common_ending|@>
  20286. endcases;@/
  20287. @<Complete a potentially long \.{\\show} command@>;
  20288. common_ending: if interaction<error_stop_mode then
  20289.   begin help0; decr(error_count);
  20290.   end
  20291. else if tracing_online>0 then
  20292.   begin@t@>@;@/
  20293.   help3("This isn't an error message; I'm just \showing something.")@/
  20294.   ("Type `I\show...' to show more (e.g., \show\cs,")@/
  20295.   ("\showthe\count10, \showbox255, \showlists).");
  20296.   end
  20297. else  begin@t@>@;@/
  20298.   help5("This isn't an error message; I'm just \showing something.")@/
  20299.   ("Type `I\show...' to show more (e.g., \show\cs,")@/
  20300.   ("\showthe\count10, \showbox255, \showlists).")@/
  20301.   ("And type `I\tracingonline=1\show...' to show boxes and")@/
  20302.   ("lists on your terminal as well as in the transcript file.");
  20303.   end;
  20304. error;
  20305. @ @<Show the current meaning of a token...@>=
  20306. begin get_token;
  20307. if interaction=error_stop_mode then wake_up_terminal;
  20308. print_nl("> ");
  20309. if cur_cs<>0 then
  20310.   begin sprint_cs(cur_cs); print_char("=");
  20311.   end;
  20312. print_meaning; goto common_ending;
  20313. @ @<Cases of |print_cmd_chr|...@>=
  20314. undefined_cs: print("undefined");
  20315. call: print("macro");
  20316. long_call: print_esc("long macro");
  20317. outer_call: print_esc("outer macro");
  20318. long_outer_call: begin print_esc("long"); print_esc("outer macro");
  20319.   end;
  20320. end_template: print_esc("outer endtemplate");
  20321. @ @<Show the current contents of a box@>=
  20322. begin scan_eight_bit_int; begin_diagnostic;
  20323. print_nl("> \box"); print_int(cur_val); print_char("=");
  20324. if box(cur_val)=null then print("void")
  20325. else show_box(box(cur_val));
  20326. @ @<Show the current value of some parameter...@>=
  20327. begin p:=the_toks;
  20328. if interaction=error_stop_mode then wake_up_terminal;
  20329. print_nl("> "); token_show(temp_head);
  20330. flush_list(link(temp_head)); goto common_ending;
  20331. @ @<Complete a potentially long \.{\\show} command@>=
  20332. end_diagnostic(true); print_err("OK");
  20333. @.OK@>
  20334. if selector=term_and_log then if tracing_online<=0 then
  20335.   begin selector:=term_only; print(" (see the transcript file)");
  20336.   selector:=term_and_log;
  20337.   end
  20338. @* \[50] Dumping and undumping the tables.
  20339. After \.{INITEX} has seen a collection of fonts and macros, it
  20340. can write all the necessary information on an auxiliary file so
  20341. that production versions of \TeX\ are able to initialize their
  20342. memory at high speed. The present section of the program takes
  20343. care of such output and input. We shall consider simultaneously
  20344. the processes of storing and restoring,
  20345. so that the inverse relation between them is clear.
  20346. @.INITEX@>
  20347. The global variable |format_ident| is a string that is printed right
  20348. after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
  20349. string says simply `\.{(INITEX)}'; for other versions of \TeX\ it says,
  20350. for example, `\.{(preloaded format=plain 82.11.19)}', showing the year,
  20351. month, and day that the format file was created. We have |format_ident=0|
  20352. before \TeX's tables are loaded.
  20353. @<Glob...@>=
  20354. @!format_ident:str_number;
  20355. @ @<Set init...@>=
  20356. format_ident:=0;
  20357. @ @<Initialize table entries...@>=
  20358. format_ident:=" (INITEX)";
  20359. @ @<Declare act...@>=
  20360. @!init procedure store_fmt_file;
  20361. label found1,found2,done1,done2;
  20362. var j,@!k,@!l:integer; {all-purpose indices}
  20363. @!p,@!q: pointer; {all-purpose pointers}
  20364. @!x: integer; {something to dump}
  20365. @!w: four_quarters; {four ASCII codes}
  20366. begin @<If dumping is not allowed, abort@>;
  20367. @<Create the |format_ident|, open the format file,
  20368.   and inform the user that dumping has begun@>;
  20369. @<Dump constants for consistency check@>;
  20370. @<Dump the string pool@>;
  20371. @<Dump the dynamic memory@>;
  20372. @<Dump the table of equivalents@>;
  20373. @<Dump the font information@>;
  20374. @<Dump the hyphenation tables@>;
  20375. @<Dump a couple more things and the closing check word@>;
  20376. @<Close the format file@>;
  20377. @ Corresponding to the procedure that dumps a format file, we have a function
  20378. that reads one in. The function returns |false| if the dumped format is
  20379. incompatible with the present \TeX\ table sizes, etc.
  20380. @d bad_fmt=6666 {go here if the format file is unacceptable}
  20381. @d too_small(#)==begin wake_up_terminal;
  20382.   wterm_ln('---! Must increase the ',#);
  20383. @.Must increase the x@>
  20384.   goto bad_fmt;
  20385.   end
  20386. @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
  20387. function load_fmt_file:boolean;
  20388. label bad_fmt,exit;
  20389. var j,@!k:integer; {all-purpose indices}
  20390. @!p,@!q: pointer; {all-purpose pointers}
  20391. @!x: integer; {something undumped}
  20392. @!w: four_quarters; {four ASCII codes}
  20393. begin @<Undump constants for consistency check@>;
  20394. @<Undump the string pool@>;
  20395. @<Undump the dynamic memory@>;
  20396. @<Undump the table of equivalents@>;
  20397. @<Undump the font information@>;
  20398. @<Undump the hyphenation tables@>;
  20399. @<Undump a couple more things and the closing check word@>;
  20400. load_fmt_file:=true; return; {it worked!}
  20401. bad_fmt: wake_up_terminal;
  20402.   wterm_ln('(Fatal format file error; I''m stymied)');
  20403. @.Fatal format file error@>
  20404. load_fmt_file:=false;
  20405. exit:end;
  20406. @ The user is not allowed to dump a format file unless |save_ptr=0|.
  20407. This condition implies that |cur_level=level_one|, hence
  20408. the |xeq_level| array is constant and it need not be dumped.
  20409. @<If dumping is not allowed, abort@>=
  20410. if save_ptr<>0 then
  20411.   begin print_err("You can't dump inside a group");
  20412. @.You can't dump...@>
  20413.   help1("`{...\dump}' is a no-no."); succumb;
  20414.   end
  20415. @ Format files consist of |memory_word| items, and we use the following
  20416. macros to dump words of different types:
  20417. @d dump_wd(#)==begin fmt_file^:=#; put(fmt_file);@+end
  20418. @d dump_int(#)==begin fmt_file^.int:=#; put(fmt_file);@+end
  20419. @d dump_hh(#)==begin fmt_file^.hh:=#; put(fmt_file);@+end
  20420. @d dump_qqqq(#)==begin fmt_file^.qqqq:=#; put(fmt_file);@+end
  20421. @<Glob...@>=
  20422. @!fmt_file:word_file; {for input or output of format information}
  20423. @ The inverse macros are slightly more complicated, since we need to check
  20424. the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
  20425. read an integer value |x| that is supposed to be in the range |a<=x<=b|.
  20426. @d undump_wd(#)==begin get(fmt_file); #:=fmt_file^;@+end
  20427. @d undump_int(#)==begin get(fmt_file); #:=fmt_file^.int;@+end
  20428. @d undump_hh(#)==begin get(fmt_file); #:=fmt_file^.hh;@+end
  20429. @d undump_qqqq(#)==begin get(fmt_file); #:=fmt_file^.qqqq;@+end
  20430. @d undump_end_end(#)==#:=x;@+end
  20431. @d undump_end(#)==(x>#) then goto bad_fmt@+else undump_end_end
  20432. @d undump(#)==begin undump_int(x); if (x<#) or undump_end
  20433. @d undump_size_end_end(#)==too_small(#)@+else undump_end_end
  20434. @d undump_size_end(#)==if x># then undump_size_end_end
  20435. @d undump_size(#)==begin undump_int(x);
  20436.   if x<# then goto bad_fmt; undump_size_end
  20437. @ The next few sections of the program should make it clear how we use the
  20438. dump/undump macros.
  20439. @<Dump constants for consistency check@>=
  20440. dump_int(@$);@/
  20441. dump_int(mem_bot);@/
  20442. dump_int(mem_top);@/
  20443. dump_int(eqtb_size);@/
  20444. dump_int(hash_prime);@/
  20445. dump_int(hyph_size)
  20446. @ Sections of a \.{WEB} program that are ``commented out'' still contribute
  20447. strings to the string pool; therefore \.{INITEX} and \TeX\ will have
  20448. the same strings. (And it is, of course, a good thing that they do.)
  20449. @.WEB@>
  20450. @^string pool@>
  20451. @<Undump constants for consistency check@>=
  20452. x:=fmt_file^.int;
  20453. if x<>@$ then goto bad_fmt; {check that strings are the same}
  20454. undump_int(x);
  20455. if x<>mem_bot then goto bad_fmt;
  20456. undump_int(x);
  20457. if x<>mem_top then goto bad_fmt;
  20458. undump_int(x);
  20459. if x<>eqtb_size then goto bad_fmt;
  20460. undump_int(x);
  20461. if x<>hash_prime then goto bad_fmt;
  20462. undump_int(x);
  20463. if x<>hyph_size then goto bad_fmt
  20464. @ @d dump_four_ASCII==
  20465.   w.b0:=qi(so(str_pool[k])); w.b1:=qi(so(str_pool[k+1]));
  20466.   w.b2:=qi(so(str_pool[k+2])); w.b3:=qi(so(str_pool[k+3]));
  20467.   dump_qqqq(w)
  20468. @<Dump the string pool@>=
  20469. dump_int(pool_ptr);
  20470. dump_int(str_ptr);
  20471. for k:=0 to str_ptr do dump_int(str_start[k]);
  20472. k:=0;
  20473. while k+4<pool_ptr do
  20474.   begin dump_four_ASCII; k:=k+4;
  20475.   end;
  20476. k:=pool_ptr-4; dump_four_ASCII;
  20477. print_ln; print_int(str_ptr); print(" strings of total length ");
  20478. print_int(pool_ptr)
  20479. @ @d undump_four_ASCII==
  20480.   undump_qqqq(w);
  20481.   str_pool[k]:=si(qo(w.b0)); str_pool[k+1]:=si(qo(w.b1));
  20482.   str_pool[k+2]:=si(qo(w.b2)); str_pool[k+3]:=si(qo(w.b3))
  20483. @<Undump the string pool@>=
  20484. undump_size(0)(pool_size)('string pool size')(pool_ptr);
  20485. undump_size(0)(max_strings)('max strings')(str_ptr);
  20486. for k:=0 to str_ptr do undump(0)(pool_ptr)(str_start[k]);
  20487. k:=0;
  20488. while k+4<pool_ptr do
  20489.   begin undump_four_ASCII; k:=k+4;
  20490.   end;
  20491. k:=pool_ptr-4; undump_four_ASCII;
  20492. init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr
  20493. @ By sorting the list of available spaces in the variable-size portion of
  20494. |mem|, we are usually able to get by without having to dump very much
  20495. of the dynamic memory.
  20496. We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
  20497. information even when it has not been gathering statistics.
  20498. @<Dump the dynamic memory@>=
  20499. sort_avail; var_used:=0;
  20500. dump_int(lo_mem_max); dump_int(rover);
  20501. p:=mem_bot; q:=rover; x:=0;
  20502. repeat for k:=p to q+1 do dump_wd(mem[k]);
  20503. x:=x+q+2-p; var_used:=var_used+q-p;
  20504. p:=q+node_size(q); q:=rlink(q);
  20505. until q=rover;
  20506. var_used:=var_used+lo_mem_max-p; dyn_used:=mem_end+1-hi_mem_min;@/
  20507. for k:=p to lo_mem_max do dump_wd(mem[k]);
  20508. x:=x+lo_mem_max+1-p;
  20509. dump_int(hi_mem_min); dump_int(avail);
  20510. for k:=hi_mem_min to mem_end do dump_wd(mem[k]);
  20511. x:=x+mem_end+1-hi_mem_min;
  20512. p:=avail;
  20513. while p<>null do
  20514.   begin decr(dyn_used); p:=link(p);
  20515.   end;
  20516. dump_int(var_used); dump_int(dyn_used);
  20517. print_ln; print_int(x);
  20518. print(" memory locations dumped; current usage is ");
  20519. print_int(var_used); print_char("&"); print_int(dyn_used)
  20520. @ @<Undump the dynamic memory@>=
  20521. undump(lo_mem_stat_max+1000)(hi_mem_stat_min-1)(lo_mem_max);
  20522. undump(lo_mem_stat_max+1)(lo_mem_max)(rover);
  20523. p:=mem_bot; q:=rover;
  20524. repeat for k:=p to q+1 do undump_wd(mem[k]);
  20525. p:=q+node_size(q);
  20526. if (p>lo_mem_max)or((q>=rlink(q))and(rlink(q)<>rover)) then goto bad_fmt;
  20527. q:=rlink(q);
  20528. until q=rover;
  20529. for k:=p to lo_mem_max do undump_wd(mem[k]);
  20530. if mem_min<mem_bot-2 then {make more low memory available}
  20531.   begin p:=llink(rover); q:=mem_min+1;
  20532.   link(mem_min):=null; info(mem_min):=null; {we don't use the bottom word}
  20533.   rlink(p):=q; llink(rover):=q;@/
  20534.   rlink(q):=rover; llink(q):=p; link(q):=empty_flag;
  20535.   node_size(q):=mem_bot-q;
  20536.   end;
  20537. undump(lo_mem_max+1)(hi_mem_stat_min)(hi_mem_min);
  20538. undump(null)(mem_top)(avail); mem_end:=mem_top;
  20539. for k:=hi_mem_min to mem_end do undump_wd(mem[k]);
  20540. undump_int(var_used); undump_int(dyn_used)
  20541. @ @<Dump the table of equivalents@>=
  20542. @<Dump regions 1 to 4 of |eqtb|@>;
  20543. @<Dump regions 5 and 6 of |eqtb|@>;
  20544. dump_int(par_loc); dump_int(write_loc);@/
  20545. @<Dump the hash table@>
  20546. @ @<Undump the table of equivalents@>=
  20547. @<Undump regions 1 to 6 of |eqtb|@>;
  20548. undump(hash_base)(frozen_control_sequence)(par_loc);
  20549. par_token:=cs_token_flag+par_loc;@/
  20550. undump(hash_base)(frozen_control_sequence)(write_loc);@/
  20551. @<Undump the hash table@>
  20552. @ The table of equivalents usually contains repeated information, so we dump it
  20553. in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
  20554. format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
  20555. copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
  20556. @<Dump regions 1 to 4 of |eqtb|@>=
  20557. k:=active_base;
  20558. repeat j:=k;
  20559. while j<int_base-1 do
  20560.   begin if (equiv(j)=equiv(j+1))and(eq_type(j)=eq_type(j+1))and@|
  20561.     (eq_level(j)=eq_level(j+1)) then goto found1;
  20562.   incr(j);
  20563.   end;
  20564. l:=int_base; goto done1; {|j=int_base-1|}
  20565. found1: incr(j); l:=j;
  20566. while j<int_base-1 do
  20567.   begin if (equiv(j)<>equiv(j+1))or(eq_type(j)<>eq_type(j+1))or@|
  20568.     (eq_level(j)<>eq_level(j+1)) then goto done1;
  20569.   incr(j);
  20570.   end;
  20571. done1:dump_int(l-k);
  20572. while k<l do
  20573.   begin dump_wd(eqtb[k]); incr(k);
  20574.   end;
  20575. k:=j+1; dump_int(k-l);
  20576. until k=int_base
  20577. @ @<Dump regions 5 and 6 of |eqtb|@>=
  20578. repeat j:=k;
  20579. while j<eqtb_size do
  20580.   begin if eqtb[j].int=eqtb[j+1].int then goto found2;
  20581.   incr(j);
  20582.   end;
  20583. l:=eqtb_size+1; goto done2; {|j=eqtb_size|}
  20584. found2: incr(j); l:=j;
  20585. while j<eqtb_size do
  20586.   begin if eqtb[j].int<>eqtb[j+1].int then goto done2;
  20587.   incr(j);
  20588.   end;
  20589. done2:dump_int(l-k);
  20590. while k<l do
  20591.   begin dump_wd(eqtb[k]); incr(k);
  20592.   end;
  20593. k:=j+1; dump_int(k-l);
  20594. until k>eqtb_size
  20595. @ @<Undump regions 1 to 6 of |eqtb|@>=
  20596. k:=active_base;
  20597. repeat undump_int(x);
  20598. if (x<1)or(k+x>eqtb_size+1) then goto bad_fmt;
  20599. for j:=k to k+x-1 do undump_wd(eqtb[j]);
  20600. k:=k+x;
  20601. undump_int(x);
  20602. if (x<0)or(k+x>eqtb_size+1) then goto bad_fmt;
  20603. for j:=k to k+x-1 do eqtb[j]:=eqtb[k-1];
  20604. k:=k+x;
  20605. until k>eqtb_size
  20606. @ A different scheme is used to compress the hash table, since its lower
  20607. region is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output
  20608. two words, |p| and |hash[p]|. The hash table is, of course, densely packed
  20609. for |p>=hash_used|, so the remaining entries are output in a~block.
  20610. @<Dump the hash table@>=
  20611. dump_int(hash_used); cs_count:=frozen_control_sequence-1-hash_used;
  20612. for p:=hash_base to hash_used do if text(p)<>0 then
  20613.   begin dump_int(p); dump_hh(hash[p]); incr(cs_count);
  20614.   end;
  20615. for p:=hash_used+1 to undefined_control_sequence-1 do dump_hh(hash[p]);
  20616. dump_int(cs_count);@/
  20617. print_ln; print_int(cs_count); print(" multiletter control sequences")
  20618. @ @<Undump the hash table@>=
  20619. undump(hash_base)(frozen_control_sequence)(hash_used); p:=hash_base-1;
  20620. repeat undump(p+1)(hash_used)(p); undump_hh(hash[p]);
  20621. until p=hash_used;
  20622. for p:=hash_used+1 to undefined_control_sequence-1 do undump_hh(hash[p]);
  20623. undump_int(cs_count)
  20624. @ @<Dump the font information@>=
  20625. dump_int(fmem_ptr);
  20626. for k:=0 to fmem_ptr-1 do dump_wd(font_info[k]);
  20627. dump_int(font_ptr);
  20628. for k:=null_font to font_ptr do
  20629.   @<Dump the array info for internal font number |k|@>;
  20630. print_ln; print_int(fmem_ptr-7); print(" words of font info for ");
  20631. print_int(font_ptr-font_base); print(" preloaded font");
  20632. if font_ptr<>font_base+1 then print_char("s")
  20633. @ @<Undump the font information@>=
  20634. undump_size(7)(font_mem_size)('font mem size')(fmem_ptr);
  20635. for k:=0 to fmem_ptr-1 do undump_wd(font_info[k]);
  20636. undump_size(font_base)(font_max)('font max')(font_ptr);
  20637. for k:=null_font to font_ptr do
  20638.   @<Undump the array info for internal font number |k|@>
  20639. @ @<Dump the array info for internal font number |k|@>=
  20640. begin dump_qqqq(font_check[k]);
  20641. dump_int(font_size[k]);
  20642. dump_int(font_dsize[k]);
  20643. dump_int(font_params[k]);@/
  20644. dump_int(hyphen_char[k]);
  20645. dump_int(skew_char[k]);@/
  20646. dump_int(font_name[k]);
  20647. dump_int(font_area[k]);@/
  20648. dump_int(font_bc[k]);
  20649. dump_int(font_ec[k]);@/
  20650. dump_int(char_base[k]);
  20651. dump_int(width_base[k]);
  20652. dump_int(height_base[k]);@/
  20653. dump_int(depth_base[k]);
  20654. dump_int(italic_base[k]);
  20655. dump_int(lig_kern_base[k]);@/
  20656. dump_int(kern_base[k]);
  20657. dump_int(exten_base[k]);
  20658. dump_int(param_base[k]);@/
  20659. dump_int(font_glue[k]);@/
  20660. dump_int(bchar_label[k]);
  20661. dump_int(font_bchar[k]);
  20662. dump_int(font_false_bchar[k]);@/
  20663. print_nl("\font"); print_esc(font_id_text(k)); print_char("=");
  20664. print_file_name(font_name[k],font_area[k],"");
  20665. if font_size[k]<>font_dsize[k] then
  20666.   begin print(" at "); print_scaled(font_size[k]); print("pt");
  20667.   end;
  20668. @ @<Undump the array info for internal font number |k|@>=
  20669. begin undump_qqqq(font_check[k]);@/
  20670. undump_int(font_size[k]);
  20671. undump_int(font_dsize[k]);
  20672. undump(min_halfword)(max_halfword)(font_params[k]);@/
  20673. undump_int(hyphen_char[k]);
  20674. undump_int(skew_char[k]);@/
  20675. undump(0)(str_ptr)(font_name[k]);
  20676. undump(0)(str_ptr)(font_area[k]);@/
  20677. undump(0)(255)(font_bc[k]);
  20678. undump(0)(255)(font_ec[k]);@/
  20679. undump_int(char_base[k]);
  20680. undump_int(width_base[k]);
  20681. undump_int(height_base[k]);@/
  20682. undump_int(depth_base[k]);
  20683. undump_int(italic_base[k]);
  20684. undump_int(lig_kern_base[k]);@/
  20685. undump_int(kern_base[k]);
  20686. undump_int(exten_base[k]);
  20687. undump_int(param_base[k]);@/
  20688. undump(min_halfword)(lo_mem_max)(font_glue[k]);@/
  20689. undump(0)(fmem_ptr-1)(bchar_label[k]);
  20690. undump(min_quarterword)(non_char)(font_bchar[k]);
  20691. undump(min_quarterword)(non_char)(font_false_bchar[k]);
  20692. @ @<Dump the hyphenation tables@>=
  20693. dump_int(hyph_count);
  20694. for k:=0 to hyph_size do if hyph_word[k]<>0 then
  20695.   begin dump_int(k); dump_int(hyph_word[k]); dump_int(hyph_list[k]);
  20696.   end;
  20697. print_ln; print_int(hyph_count); print(" hyphenation exception");
  20698. if hyph_count<>1 then print_char("s");
  20699. if trie_not_ready then init_trie;
  20700. dump_int(trie_max);
  20701. for k:=0 to trie_max do dump_hh(trie[k]);
  20702. dump_int(trie_op_ptr);
  20703. for k:=1 to trie_op_ptr do
  20704.   begin dump_int(hyf_distance[k]);
  20705.   dump_int(hyf_num[k]);
  20706.   dump_int(hyf_next[k]);
  20707.   end;
  20708. print_nl("Hyphenation trie of length "); print_int(trie_max);
  20709. @.Hyphenation trie...@>
  20710. print(" has "); print_int(trie_op_ptr); print(" op");
  20711. if trie_op_ptr<>1 then print_char("s");
  20712. print(" out of "); print_int(trie_op_size);
  20713. for k:=255 downto 0 do if trie_used[k]>min_quarterword then
  20714.   begin print_nl("  "); print_int(qo(trie_used[k]));
  20715.   print(" for language "); print_int(k);
  20716.   dump_int(k); dump_int(qo(trie_used[k]));
  20717.   end
  20718. @ Only ``nonempty'' parts of |op_start| need to be restored.
  20719. @<Undump the hyphenation tables@>=
  20720. undump(0)(hyph_size)(hyph_count);
  20721. for k:=1 to hyph_count do
  20722.   begin undump(0)(hyph_size)(j);
  20723.   undump(0)(str_ptr)(hyph_word[j]);
  20724.   undump(min_halfword)(max_halfword)(hyph_list[j]);
  20725.   end;
  20726. undump_size(0)(trie_size)('trie size')(j); @+init trie_max:=j;@+tini
  20727. for k:=0 to j do undump_hh(trie[k]);
  20728. undump_size(0)(trie_op_size)('trie op size')(j); @+init trie_op_ptr:=j;@+tini
  20729. for k:=1 to j do
  20730.   begin undump(0)(63)(hyf_distance[k]); {a |small_number|}
  20731.   undump(0)(63)(hyf_num[k]);
  20732.   undump(min_quarterword)(max_quarterword)(hyf_next[k]);
  20733.   end;
  20734. init for k:=0 to 255 do trie_used[k]:=min_quarterword;@+tini@;@/
  20735. k:=256;
  20736. while j>0 do
  20737.   begin undump(0)(k-1)(k); undump(1)(j)(x);@+init trie_used[k]:=qi(x);@+tini@;@/
  20738.   j:=j-x; op_start[k]:=qo(j);
  20739.   end;
  20740. @!init trie_not_ready:=false @+tini
  20741. @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
  20742. to prevent them appearing again.
  20743. @<Dump a couple more things and the closing check word@>=
  20744. dump_int(interaction); dump_int(format_ident); dump_int(69069);
  20745. tracing_stats:=0
  20746. @ @<Undump a couple more things and the closing check word@>=
  20747. undump(batch_mode)(error_stop_mode)(interaction);
  20748. undump(0)(str_ptr)(format_ident);
  20749. undump_int(x);
  20750. if (x<>69069)or eof(fmt_file) then goto bad_fmt
  20751. @ @<Create the |format_ident|...@>=
  20752. selector:=new_string;
  20753. print(" (preloaded format="); print(job_name); print_char(" ");
  20754. print_int(year mod 100); print_char(".");
  20755. print_int(month); print_char("."); print_int(day); print_char(")");
  20756. if interaction=batch_mode then selector:=log_only
  20757. else selector:=term_and_log;
  20758. str_room(1);
  20759. format_ident:=make_string;
  20760. pack_job_name(format_extension);
  20761. while not w_open_out(fmt_file) do
  20762.   prompt_file_name("format file name",format_extension);
  20763. print_nl("Beginning to dump on file ");
  20764. @.Beginning to dump...@>
  20765. slow_print(w_make_name_string(fmt_file)); flush_string;
  20766. print_nl(""); slow_print(format_ident)
  20767. @ @<Close the format file@>=
  20768. w_close(fmt_file)
  20769. @* \[51] The main program.
  20770. This is it: the part of \TeX\ that executes all those procedures we have
  20771. written.
  20772. Well---almost. Let's leave space for a few more routines that we may
  20773. have forgotten.
  20774. @p @<Last-minute procedures@>
  20775. @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
  20776. @.INITEX@>
  20777. has to be run first; it initializes everything from scratch, without
  20778. reading a format file, and it has the capability of dumping a format file.
  20779. The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
  20780. @.VIRTEX@>
  20781. to input a format file in order to get started. \.{VIRTEX} typically has
  20782. more memory capacity than \.{INITEX}, because it does not need the space
  20783. consumed by the auxiliary hyphenation tables and the numerous calls on
  20784. |primitive|, etc.
  20785. The \.{VIRTEX} program cannot read a format file instantaneously, of course;
  20786. the best implementations therefore allow for production versions of \TeX\ that
  20787. not only avoid the loading routine for \PASCAL\ object code, they also have
  20788. a format file pre-loaded. This is impossible to do if we stick to standard
  20789. \PASCAL; but there is a simple way to fool many systems into avoiding the
  20790. initialization, as follows:\quad(1)~We declare a global integer variable
  20791. called |ready_already|. The probability is negligible that this
  20792. variable holds any particular value like 314159 when \.{VIRTEX} is first
  20793. loaded.\quad(2)~After we have read in a format file and initialized
  20794. everything, we set |ready_already:=314159|.\quad(3)~Soon \.{VIRTEX}
  20795. will print `\.*', waiting for more input; and at this point we
  20796. interrupt the program and save its core image in some form that the
  20797. operating system can reload speedily.\quad(4)~When that core image is
  20798. activated, the program starts again at the beginning; but now
  20799. |ready_already=314159| and all the other global variables have
  20800. their initial values too. The former chastity has vanished!
  20801. In other words, if we allow ourselves to test the condition
  20802. |ready_already=314159|, before |ready_already| has been
  20803. assigned a value, we can avoid the lengthy initialization. Dirty tricks
  20804. rarely pay off so handsomely.
  20805. @^dirty \PASCAL@>
  20806. @^system dependencies@>
  20807. On systems that allow such preloading, the standard program called \.{TeX}
  20808. should be the one that has \.{plain} format preloaded, since that agrees
  20809. with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
  20810. @:TeXbook}{\sl The \TeX book@>
  20811. @.AmSTeX@>
  20812. @.plain@>
  20813. be provided for commonly used formats.
  20814. @<Glob...@>=
  20815. @!ready_already:integer; {a sacrifice of purity for economy}
  20816. @ Now this is really it: \TeX\ starts and ends here.
  20817. The initial test involving |ready_already| should be deleted if the
  20818. \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
  20819. @^system dependencies@>
  20820. @p begin @!{|start_here|}
  20821. history:=fatal_error_stop; {in case we quit during initialization}
  20822. t_open_out; {open the terminal for output}
  20823. if ready_already=314159 then goto start_of_TEX;
  20824. @<Check the ``constant'' values...@>@;
  20825. if bad>0 then
  20826.   begin wterm_ln('Ouch---my internal constants have been clobbered!',
  20827.     '---case ',bad:1);
  20828. @.Ouch...clobbered@>
  20829.   goto final_end;
  20830.   end;
  20831. initialize; {set global variables to their starting values}
  20832. @!init if not get_strings_started then goto final_end;
  20833. init_prim; {call |primitive| for each primitive}
  20834. init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr; fix_date_and_time;
  20835. tini@/
  20836. ready_already:=314159;
  20837. start_of_TEX: @<Initialize the output routines@>;
  20838. @<Get the first line of input and prepare to start@>;
  20839. history:=spotless; {ready to go!}
  20840. main_control; {come to life}
  20841. final_cleanup; {prepare for death}
  20842. end_of_TEX: close_files_and_terminate;
  20843. final_end: ready_already:=0;
  20844. @ Here we do whatever is needed to complete \TeX's job gracefully on the
  20845. local operating system. The code here might come into play after a fatal
  20846. error; it must therefore consist entirely of ``safe'' operations that
  20847. cannot produce error messages. For example, it would be a mistake to call
  20848. |str_room| or |make_string| at this time, because a call on |overflow|
  20849. might lead to an infinite loop.
  20850. @^system dependencies@>
  20851. Actually there's one way to get error messages, via |prepare_mag|;
  20852. but that can't cause infinite recursion.
  20853. @^recursion@>
  20854. This program doesn't bother to close the input files that may still be open.
  20855. @<Last-minute...@>=
  20856. procedure close_files_and_terminate;
  20857. var k:integer; {all-purpose index}
  20858. begin @<Finish the extensions@>;
  20859. @!stat if tracing_stats>0 then @<Output statistics about this job@>;@;@+tats@/
  20860. wake_up_terminal; @<Finish the \.{DVI} file@>;
  20861. if log_opened then
  20862.   begin wlog_cr; a_close(log_file); selector:=selector-2;
  20863.   if selector=term_only then
  20864.     begin print_nl("Transcript written on ");
  20865. @.Transcript written...@>
  20866.     slow_print(log_name); print_char(".");
  20867.     end;
  20868.   end;
  20869. @ The present section goes directly to the log file instead of using
  20870. |print| commands, because there's no need for these strings to take
  20871. up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
  20872. @<Output statistics...@>=
  20873. if log_opened then
  20874.   begin wlog_ln(' ');
  20875.   wlog_ln('Here is how much of TeX''s memory',' you used:');
  20876. @.Here is how much...@>
  20877.   wlog(' ',str_ptr-init_str_ptr:1,' string');
  20878.   if str_ptr<>init_str_ptr+1 then wlog('s');
  20879.   wlog_ln(' out of ', max_strings-init_str_ptr:1);@/
  20880.   wlog_ln(' ',pool_ptr-init_pool_ptr:1,' string characters out of ',
  20881.     pool_size-init_pool_ptr:1);@/
  20882.   wlog_ln(' ',lo_mem_max-mem_min+mem_end-hi_mem_min+2:1,@|
  20883.     ' words of memory out of ',mem_end+1-mem_min:1);@/
  20884.   wlog_ln(' ',cs_count:1,' multiletter control sequences out of ',
  20885.     hash_size:1);@/
  20886.   wlog(' ',fmem_ptr:1,' words of font info for ',
  20887.     font_ptr-font_base:1,' font');
  20888.   if font_ptr<>font_base+1 then wlog('s');
  20889.   wlog_ln(', out of ',font_mem_size:1,' for ',font_max-font_base:1);@/
  20890.   wlog(' ',hyph_count:1,' hyphenation exception');
  20891.   if hyph_count<>1 then wlog('s');
  20892.   wlog_ln(' out of ',hyph_size:1);@/
  20893.   wlog_ln(' ',max_in_stack:1,'i,',max_nest_stack:1,'n,',@|
  20894.     max_param_stack:1,'p,',@|
  20895.     max_buf_stack+1:1,'b,',@|
  20896.     max_save_stack+6:1,'s stack positions out of ',@|
  20897.     stack_size:1,'i,',
  20898.     nest_size:1,'n,',
  20899.     param_size:1,'p,',
  20900.     buf_size:1,'b,',
  20901.     save_size:1,'s');
  20902.   end
  20903. @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
  20904. been scanned and |its_all_over|\kern-2pt.
  20905. @<Last-minute...@>=
  20906. procedure final_cleanup;
  20907. label exit;
  20908. var c:small_number; {0 for \.{\\end}, 1 for \.{\\dump}}
  20909. begin c:=cur_chr;
  20910. if job_name=0 then open_log_file;
  20911. while input_ptr>0 do
  20912.   if state=token_list then end_token_list@+else end_file_reading;
  20913. while open_parens>0 do
  20914.   begin print(" )"); decr(open_parens);
  20915.   end;
  20916. if cur_level>level_one then
  20917.   begin print_nl("("); print_esc("end occurred ");
  20918.   print("inside a group at level ");
  20919. @:end_}{\.{(\\end occurred...)}@>
  20920.   print_int(cur_level-level_one); print_char(")");
  20921.   end;
  20922. while cond_ptr<>null do
  20923.   begin print_nl("("); print_esc("end occurred ");
  20924.   print("when "); print_cmd_chr(if_test,cur_if);
  20925.   if if_line<>0 then
  20926.     begin print(" on line "); print_int(if_line);
  20927.     end;
  20928.   print(" was incomplete)");
  20929.   if_line:=if_line_field(cond_ptr);
  20930.   cur_if:=subtype(cond_ptr); temp_ptr:=cond_ptr;
  20931.   cond_ptr:=link(cond_ptr); free_node(temp_ptr,if_node_size);
  20932.   end;
  20933. if history<>spotless then
  20934.  if ((history=warning_issued)or(interaction<error_stop_mode)) then
  20935.   if selector=term_and_log then
  20936.   begin selector:=term_only;
  20937.   print_nl("(see the transcript file for additional information)");
  20938. @.see the transcript file...@>
  20939.   selector:=term_and_log;
  20940.   end;
  20941. if c=1 then
  20942.   begin @!init for c:=top_mark_code to split_bot_mark_code do
  20943.     if cur_mark[c]<>null then delete_token_ref(cur_mark[c]);
  20944.   store_fmt_file; return;@+tini@/
  20945.   print_nl("(\dump is performed only by INITEX)"); return;
  20946. @:dump_}{\.{\\dump...only by INITEX}@>
  20947.   end;
  20948. exit:end;
  20949. @ @<Last-minute...@>=
  20950. @!init procedure init_prim; {initialize all the primitives}
  20951. begin no_new_control_sequence:=false;
  20952. @<Put each...@>;
  20953. no_new_control_sequence:=true;
  20954. @ When we begin the following code, \TeX's tables may still contain garbage;
  20955. the strings might not even be present. Thus we must proceed cautiously to get
  20956. bootstrapped in.
  20957. But when we finish this part of the program, \TeX\ is ready to call on the
  20958. |main_control| routine to do its work.
  20959. @<Get the first line...@>=
  20960. begin @<Initialize the input routines@>;
  20961. if (format_ident=0)or(buffer[loc]="&") then
  20962.   begin if format_ident<>0 then initialize; {erase preloaded format}
  20963.   if not open_fmt_file then goto final_end;
  20964.   if not load_fmt_file then
  20965.     begin w_close(fmt_file); goto final_end;
  20966.     end;
  20967.   w_close(fmt_file);
  20968.   while (loc<limit)and(buffer[loc]=" ") do incr(loc);
  20969.   end;
  20970. if end_line_char_inactive then decr(limit)
  20971. else  buffer[limit]:=end_line_char;
  20972. fix_date_and_time;@/
  20973. @<Compute the magic offset@>;
  20974. @<Initialize the print |selector|...@>;
  20975. if (loc<limit)and(cat_code(buffer[loc])<>escape) then start_input;
  20976.   {\.{\\input} assumed}
  20977. @* \[52] Debugging.
  20978. Once \TeX\ is working, you should be able to diagnose most errors with
  20979. the \.{\\show} commands and other diagnostic features. But for the initial
  20980. stages of debugging, and for the revelation of really deep mysteries, you
  20981. can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
  20982. checks and its debugger. An additional routine called |debug_help|
  20983. will also come into play when you type `\.D' after an error message;
  20984. |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
  20985. @^debugging@>
  20986. @^system dependencies@>
  20987. The interface to |debug_help| is primitive, but it is good enough when used
  20988. with a \PASCAL\ debugger that allows you to set breakpoints and to read
  20989. variables and change their values. After getting the prompt `\.{debug \#}', you
  20990. type either a negative number (this exits |debug_help|), or zero (this
  20991. goes to a location where you can set a breakpoint, thereby entering into
  20992. dialog with the \PASCAL\ debugger), or a positive number |m| followed by
  20993. an argument |n|. The meaning of |m| and |n| will be clear from the
  20994. program below. (If |m=13|, there is an additional argument, |l|.)
  20995. @.debug \#@>
  20996. @d breakpoint=888 {place where a breakpoint is desirable}
  20997. @<Last-minute...@>=
  20998. @!debug procedure debug_help; {routine to display various things}
  20999. label breakpoint,exit;
  21000. var k,@!l,@!m,@!n:integer;
  21001. begin loop begin wake_up_terminal;
  21002.   print_nl("debug # (-1 to exit):"); update_terminal;
  21003. @.debug \#@>
  21004.   read(term_in,m);
  21005.   if m<0 then return
  21006.   else if m=0 then
  21007.     begin goto breakpoint;@\ {go to every label at least once}
  21008.     breakpoint: m:=0; @{'BREAKPOINT'@}@\
  21009.     end
  21010.   else  begin read(term_in,n);
  21011.     case m of
  21012.     @t\4@>@<Numbered cases for |debug_help|@>@;
  21013.     othercases print("?")
  21014.     endcases;
  21015.     end;
  21016.   end;
  21017. exit:end;
  21018. gubed
  21019. @ @<Numbered cases...@>=
  21020. 1: print_word(mem[n]); {display |mem[n]| in all forms}
  21021. 2: print_int(info(n));
  21022. 3: print_int(link(n));
  21023. 4: print_word(eqtb[n]);
  21024. 5: print_word(font_info[n]);
  21025. 6: print_word(save_stack[n]);
  21026. 7: show_box(n);
  21027.   {show a box, abbreviated by |show_box_depth| and |show_box_breadth|}
  21028. 8: begin breadth_max:=10000; depth_threshold:=pool_size-pool_ptr-10;
  21029.   show_node_list(n); {show a box in its entirety}
  21030.   end;
  21031. 9: show_token_list(n,null,1000);
  21032. 10: slow_print(n);
  21033. 11: check_mem(n>0); {check wellformedness; print new busy locations if |n>0|}
  21034. 12: search_mem(n); {look for pointers to |n|}
  21035. 13: begin read(term_in,l); print_cmd_chr(n,l);
  21036.   end;
  21037. 14: for k:=0 to n do print(buffer[k]);
  21038. 15: begin font_in_short_display:=null_font; short_display(n);
  21039.   end;
  21040. 16: panicking:=not panicking;
  21041. @* \[53] Extensions.
  21042. The program above includes a bunch of ``hooks'' that allow further
  21043. capabilities to be added without upsetting \TeX's basic structure.
  21044. Most of these hooks are concerned with ``whatsit'' nodes, which are
  21045. intended to be used for special purposes; whenever a new extension to
  21046. \TeX\ involves a new kind of whatsit node, a corresponding change needs
  21047. to be made to the routines below that deal with such nodes,
  21048. but it will usually be unnecessary to make many changes to the
  21049. other parts of this program.
  21050. In order to demonstrate how extensions can be made, we shall treat
  21051. `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
  21052. `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
  21053. These commands are actually primitives of \TeX, and they should
  21054. appear in all implementations of the system; but let's try to imagine
  21055. that they aren't. Then the program below illustrates how a person
  21056. could add them.
  21057. Sometimes, of course, an extension will require changes to \TeX\ itself;
  21058. no system of hooks could be complete enough for all conceivable extensions.
  21059. The features associated with `\.{\\write}' are almost all confined to the
  21060. following paragraphs, but there are small parts of the |print_ln| and
  21061. |print_char| procedures that were introduced specifically to \.{\\write}
  21062. characters. Furthermore one of the token lists recognized by the scanner
  21063. is a |write_text|; and there are a few other miscellaneous places where we
  21064. have already provided for some aspect of \.{\\write}.  The goal of a \TeX\
  21065. extender should be to minimize alterations to the standard parts of the
  21066. program, and to avoid them completely if possible. He or she should also
  21067. be quite sure that there's no easy way to accomplish the desired goals
  21068. with the standard features that \TeX\ already has. ``Think thrice before
  21069. extending,'' because that may save a lot of work, and it will also keep
  21070. incompatible extensions of \TeX\ from proliferating.
  21071. @^system dependencies@>
  21072. @^extensions to \TeX@>
  21073. @ First let's consider the format of whatsit nodes that are used to represent
  21074. the data associated with \.{\\write} and its relatives. Recall that a whatsit
  21075. has |type=whatsit_node|, and the |subtype| is supposed to distinguish
  21076. different kinds of whatsits. Each node occupies two or more words; the
  21077. exact number is immaterial, as long as it is readily determined from the
  21078. |subtype| or other data.
  21079. We shall introduce five |subtype| values here, corresponding to the
  21080. control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
  21081. \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
  21082. that identifies the write-stream number (0 to 15, or 16 for out-of-range and
  21083. positive, or 17 for out-of-range and negative).
  21084. In the case of \.{\\write} and \.{\\special}, there is also a field that
  21085. points to the reference count of a token list that should be sent. In the
  21086. case of \.{\\openout}, we need three words and three auxiliary subfields
  21087. to hold the string numbers for name, area, and extension.
  21088. @d write_node_size=2 {number of words in a write/whatsit node}
  21089. @d open_node_size=3 {number of words in an open/whatsit node}
  21090. @d open_node=0 {|subtype| in whatsits that represent files to \.{\\openout}}
  21091. @d write_node=1 {|subtype| in whatsits that represent things to \.{\\write}}
  21092. @d close_node=2 {|subtype| in whatsits that represent streams to \.{\\closeout}}
  21093. @d special_node=3 {|subtype| in whatsits that represent \.{\\special} things}
  21094. @d language_node=4 {|subtype| in whatsits that change the current language}
  21095. @d what_lang(#)==link(#+1) {language number, in the range |0..255|}
  21096. @d what_lhm(#)==type(#+1) {minimum left fragment, in the range |1..63|}
  21097. @d what_rhm(#)==subtype(#+1) {minimum right fragment, in the range |1..63|}
  21098. @d write_tokens(#) == link(#+1) {reference count of token list to write}
  21099. @d write_stream(#) == info(#+1) {stream number (0 to 17)}
  21100. @d open_name(#) == link(#+1) {string number of file name to open}
  21101. @d open_area(#) == info(#+2) {string number of file area for |open_name|}
  21102. @d open_ext(#) == link(#+2) {string number of file extension for |open_name|}
  21103. @ The sixteen possible \.{\\write} streams are represented by the |write_file|
  21104. array. The |j|th file is open if and only if |write_open[j]=true|. The last
  21105. two streams are special; |write_open[16]| represents a stream number
  21106. greater than 15, while |write_open[17]| represents a negative stream number,
  21107. and both of these variables are always |false|.
  21108. @<Glob...@>=
  21109. @!write_file:array[0..15] of alpha_file;
  21110. @!write_open:array[0..17] of boolean;
  21111. @ @<Set init...@>=
  21112. for k:=0 to 17 do write_open[k]:=false;
  21113. @ Extensions might introduce new command codes; but it's best to use
  21114. |extension| with a modifier, whenever possible, so that |main_control|
  21115. stays the same.
  21116. @d immediate_code=4 {command modifier for \.{\\immediate}}
  21117. @d set_language_code=5 {command modifier for \.{\\setlanguage}}
  21118. @<Put each...@>=
  21119. primitive("openout",extension,open_node);@/
  21120. @!@:open_out_}{\.{\\openout} primitive@>
  21121. primitive("write",extension,write_node); write_loc:=cur_val;@/
  21122. @!@:write_}{\.{\\write} primitive@>
  21123. primitive("closeout",extension,close_node);@/
  21124. @!@:close_out_}{\.{\\closeout} primitive@>
  21125. primitive("special",extension,special_node);@/
  21126. @!@:special_}{\.{\\special} primitive@>
  21127. primitive("immediate",extension,immediate_code);@/
  21128. @!@:immediate_}{\.{\\immediate} primitive@>
  21129. primitive("setlanguage",extension,set_language_code);@/
  21130. @!@:set_language_}{\.{\\setlanguage} primitive@>
  21131. @ The variable |write_loc| just introduced is used to provide an
  21132. appropriate error message in case of ``runaway'' write texts.
  21133. @<Glob...@>=
  21134. @!write_loc:pointer; {|eqtb| address of \.{\\write}}
  21135. @ @<Cases of |print_cmd_chr|...@>=
  21136. extension: case chr_code of
  21137.   open_node:print_esc("openout");
  21138.   write_node:print_esc("write");
  21139.   close_node:print_esc("closeout");
  21140.   special_node:print_esc("special");
  21141.   immediate_code:print_esc("immediate");
  21142.   set_language_code:print_esc("setlanguage");
  21143.   othercases print("[unknown extension!]")
  21144.   endcases;
  21145. @ When an |extension| command occurs in |main_control|, in any mode,
  21146. the |do_extension| routine is called.
  21147. @<Cases of |main_control| that are for extensions...@>=
  21148. any_mode(extension):do_extension;
  21149. @ @<Declare act...@>=
  21150. @t\4@>@<Declare procedures needed in |do_extension|@>@;
  21151. procedure do_extension;
  21152. var i,@!j,@!k:integer; {all-purpose integers}
  21153. @!p,@!q,@!r:pointer; {all-purpose pointers}
  21154. begin case cur_chr of
  21155. open_node:@<Implement \.{\\openout}@>;
  21156. write_node:@<Implement \.{\\write}@>;
  21157. close_node:@<Implement \.{\\closeout}@>;
  21158. special_node:@<Implement \.{\\special}@>;
  21159. immediate_code:@<Implement \.{\\immediate}@>;
  21160. set_language_code:@<Implement \.{\\setlanguage}@>;
  21161. othercases confusion("ext1")
  21162. @:this can't happen ext1}{\quad ext1@>
  21163. endcases;
  21164. @ Here is a subroutine that creates a whatsit node having a given |subtype|
  21165. and a given number of words. It initializes only the first word of the whatsit,
  21166. and appends it to the current list.
  21167. @<Declare procedures needed in |do_extension|@>=
  21168. procedure new_whatsit(@!s:small_number;@!w:small_number);
  21169. var p:pointer; {the new node}
  21170. begin p:=get_node(w); type(p):=whatsit_node; subtype(p):=s;
  21171. link(tail):=p; tail:=p;
  21172. @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
  21173. involved, and also inserts a |write_stream| number.
  21174. @<Declare procedures needed in |do_ext...@>=
  21175. procedure new_write_whatsit(@!w:small_number);
  21176. begin new_whatsit(cur_chr,w);
  21177. if w<>write_node_size then scan_four_bit_int
  21178. else  begin scan_int;
  21179.   if cur_val<0 then cur_val:=17
  21180.   else if cur_val>15 then cur_val:=16;
  21181.   end;
  21182. write_stream(tail):=cur_val;
  21183. @ @<Implement \.{\\openout}@>=
  21184. begin new_write_whatsit(open_node_size);
  21185. scan_optional_equals; scan_file_name;@/
  21186. open_name(tail):=cur_name; open_area(tail):=cur_area; open_ext(tail):=cur_ext;
  21187. @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
  21188. without expanding its macros; the macros will be expanded later when this
  21189. token list is rescanned.
  21190. @<Implement \.{\\write}@>=
  21191. begin k:=cur_cs; new_write_whatsit(write_node_size);@/
  21192. cur_cs:=k; p:=scan_toks(false,false); write_tokens(tail):=def_ref;
  21193. @ @<Implement \.{\\closeout}@>=
  21194. begin new_write_whatsit(write_node_size); write_tokens(tail):=null;
  21195. @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
  21196. list as in \.{\\xdef} and \.{\\mark}.
  21197. @<Implement \.{\\special}@>=
  21198. begin new_whatsit(special_node,write_node_size); write_stream(tail):=null;
  21199. p:=scan_toks(false,true); write_tokens(tail):=def_ref;
  21200. @ Each new type of node that appears in our data structure must be capable
  21201. of being displayed, copied, destroyed, and so on. The routines that we
  21202. need for write-oriented whatsits are somewhat like those for mark nodes;
  21203. other extensions might, of course, involve more subtlety here.
  21204. @<Basic printing...@>=
  21205. procedure print_write_whatsit(@!s:str_number;@!p:pointer);
  21206. begin print_esc(s);
  21207. if write_stream(p)<16 then print_int(write_stream(p))
  21208. else if write_stream(p)=16 then print_char("*")
  21209. @.*\relax@>
  21210. else print_char("-");
  21211. @ @<Display the whatsit...@>=
  21212. case subtype(p) of
  21213. open_node:begin print_write_whatsit("openout",p);
  21214.   print_char("="); print_file_name(open_name(p),open_area(p),open_ext(p));
  21215.   end;
  21216. write_node:begin print_write_whatsit("write",p);
  21217.   print_mark(write_tokens(p));
  21218.   end;
  21219. close_node:print_write_whatsit("closeout",p);
  21220. special_node:begin print_esc("special");
  21221.   print_mark(write_tokens(p));
  21222.   end;
  21223. language_node:begin print_esc("setlanguage");
  21224.   print_int(what_lang(p)); print(" (hyphenmin ");
  21225.   print_int(what_lhm(p)); print_char(",");
  21226.   print_int(what_rhm(p)); print_char(")");
  21227.   end;
  21228. othercases print("whatsit?")
  21229. endcases
  21230. @ @<Make a partial copy of the whatsit...@>=
  21231. case subtype(p) of
  21232. open_node: begin r:=get_node(open_node_size); words:=open_node_size;
  21233.   end;
  21234. write_node,special_node: begin r:=get_node(write_node_size);
  21235.   add_token_ref(write_tokens(p)); words:=write_node_size;
  21236.   end;
  21237. close_node,language_node: begin r:=get_node(small_node_size);
  21238.   words:=small_node_size;
  21239.   end;
  21240. othercases confusion("ext2")
  21241. @:this can't happen ext2}{\quad ext2@>
  21242. endcases
  21243. @ @<Wipe out the whatsit...@>=
  21244. begin case subtype(p) of
  21245. open_node: free_node(p,open_node_size);
  21246. write_node,special_node: begin delete_token_ref(write_tokens(p));
  21247.   free_node(p,write_node_size); goto done;
  21248.   end;
  21249. close_node,language_node: free_node(p,small_node_size);
  21250. othercases confusion("ext3")
  21251. @:this can't happen ext3}{\quad ext3@>
  21252. endcases;@/
  21253. goto done;
  21254. @ @<Incorporate a whatsit node into a vbox@>=do_nothing
  21255. @ @<Incorporate a whatsit node into an hbox@>=do_nothing
  21256. @ @<Let |d| be the width of the whatsit |p|@>=d:=0
  21257. @ @d adv_past(#)==@+if subtype(#)=language_node then
  21258.     begin cur_lang:=what_lang(#); l_hyf:=what_lhm(#); r_hyf:=what_rhm(#);@+end
  21259. @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
  21260. adv_past(cur_p)
  21261. @ @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
  21262. adv_past(s)
  21263. @ @<Prepare to move whatsit |p| to the current page, then |goto contribute|@>=
  21264. goto contribute
  21265. @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
  21266. goto not_found
  21267. @ @<Output the whatsit node |p| in a vlist@>=
  21268. out_what(p)
  21269. @ @<Output the whatsit node |p| in an hlist@>=
  21270. out_what(p)
  21271. @ After all this preliminary shuffling, we come finally to the routines
  21272. that actually send out the requested data. Let's do \.{\\special} first
  21273. (it's easier).
  21274. @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21275. procedure special_out(@!p:pointer);
  21276. var old_setting:0..max_selector; {holds print |selector|}
  21277. @!k:pool_pointer; {index into |str_pool|}
  21278. begin synch_h; synch_v;@/
  21279. old_setting:=selector; selector:=new_string;
  21280. show_token_list(link(write_tokens(p)),null,pool_size-pool_ptr);
  21281. selector:=old_setting;
  21282. str_room(1);
  21283. if cur_length<256 then
  21284.   begin dvi_out(xxx1); dvi_out(cur_length);
  21285.   end
  21286. else  begin dvi_out(xxx4); dvi_four(cur_length);
  21287.   end;
  21288. for k:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[k]));
  21289. pool_ptr:=str_start[str_ptr]; {erase the string}
  21290. @ To write a token list, we must run it through \TeX's scanner, expanding
  21291. macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
  21292. if a delimited macro parameter isn't matched, and runaways would be
  21293. extremely confusing since we are calling on \TeX's scanner in the middle
  21294. of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
  21295. a ``stopper,'' right after the token list. This control sequence is
  21296. artificially defined to be \.{\\outer}.
  21297. @:end_write_}{\.{\\endwrite}@>
  21298. @<Initialize table...@>=
  21299. text(end_write):="endwrite"; eq_level(end_write):=level_one;
  21300. eq_type(end_write):=outer_call; equiv(end_write):=null;
  21301. @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21302. procedure write_out(@!p:pointer);
  21303. var old_setting:0..max_selector; {holds print |selector|}
  21304. @!old_mode:integer; {saved |mode|}
  21305. @!j:small_number; {write stream number}
  21306. @!q,@!r:pointer; {temporary variables for list manipulation}
  21307. begin @<Expand macros in the token list
  21308.   and make |link(def_ref)| point to the result@>;
  21309. old_setting:=selector; j:=write_stream(p);
  21310. if write_open[j] then selector:=j
  21311. else  begin {write to the terminal if file isn't open}
  21312.   if (j=17)and(selector=term_and_log) then selector:=log_only;
  21313.   print_nl("");
  21314.   end;
  21315. token_show(def_ref); print_ln;
  21316. flush_list(def_ref); selector:=old_setting;
  21317. @ The final line of this routine is slightly subtle; at least, the author
  21318. didn't think about it until getting burnt! There is a used-up token list
  21319. @^Knuth, Donald Ervin@>
  21320. on the stack, namely the one that contained |end_write_token|. (We
  21321. insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
  21322. above.) If it were not removed, and if there were numerous writes on a
  21323. single page, the stack would overflow.
  21324. @d end_write_token==cs_token_flag+end_write
  21325. @<Expand macros in the token list and...@>=
  21326. q:=get_avail; info(q):=right_brace_token+"}";@/
  21327. r:=get_avail; link(q):=r; info(r):=end_write_token; ins_list(q);@/
  21328. begin_token_list(write_tokens(p),write_text);@/
  21329. q:=get_avail; info(q):=left_brace_token+"{"; ins_list(q);
  21330. {now we're ready to scan
  21331.   `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'}
  21332. old_mode:=mode; mode:=0;
  21333.   {disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}}
  21334. cur_cs:=write_loc; q:=scan_toks(false,true); {expand macros, etc.}
  21335. get_token;@+if cur_tok<>end_write_token then
  21336.   @<Recover from an unbalanced write command@>;
  21337. mode:=old_mode;
  21338. end_token_list {conserve stack space}
  21339. @ @<Recover from an unbalanced write command@>=
  21340. begin print_err("Unbalanced write command");
  21341. @.Unbalanced write...@>
  21342. help2("On this page there's a \write with fewer real {'s than }'s.")@/
  21343. ("I can't handle that very well; good luck."); error;
  21344. repeat get_token;
  21345. until cur_tok=end_write_token;
  21346. @ The |out_what| procedure takes care of outputting whatsit nodes for
  21347. |vlist_out| and |hlist_out|\kern-.3pt.
  21348. @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21349. procedure out_what(@!p:pointer);
  21350. var j:small_number; {write stream number}
  21351. begin case subtype(p) of
  21352. open_node,write_node,close_node:@<Do some work that has been queued up
  21353.   for \.{\\write}@>;
  21354. special_node:special_out(p);
  21355. language_node:do_nothing;
  21356. othercases confusion("ext4")
  21357. @:this can't happen ext4}{\quad ext4@>
  21358. endcases;
  21359. @ We don't implement \.{\\write} inside of leaders. (The reason is that
  21360. the number of times a leader box appears might be different in different
  21361. implementations, due to machine-dependent rounding in the glue calculations.)
  21362. @^leaders@>
  21363. @<Do some work that has been queued up...@>=
  21364. if not doing_leaders then
  21365.   begin j:=write_stream(p);
  21366.   if subtype(p)=write_node then write_out(p)
  21367.   else  begin if write_open[j] then a_close(write_file[j]);
  21368.     if subtype(p)=close_node then write_open[j]:=false
  21369.     else if j<16 then
  21370.       begin cur_name:=open_name(p); cur_area:=open_area(p);
  21371.       cur_ext:=open_ext(p);
  21372.       if cur_ext="" then cur_ext:=".tex";
  21373.       pack_cur_name;
  21374.       while not a_open_out(write_file[j]) do
  21375.         prompt_file_name("output file name",".tex");
  21376.       write_open[j]:=true;
  21377.       end;
  21378.     end;
  21379.   end
  21380. @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
  21381. to descend to one level of recursion. Nothing happens unless \.{\\immediate}
  21382. is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
  21383. @^recursion@>
  21384. @<Implement \.{\\immediate}@>=
  21385. begin get_x_token;
  21386. if (cur_cmd=extension)and(cur_chr<=close_node) then
  21387.   begin p:=tail; do_extension; {append a whatsit node}
  21388.   out_what(tail); {do the action immediately}
  21389.   flush_node_list(tail); tail:=p; link(p):=null;
  21390.   end
  21391. else back_input;
  21392. @ The \.{\\language} extension is somewhat different.
  21393. We need a subroutine that comes into play when a character of
  21394. a non-|clang| language is being appended to the current paragraph.
  21395. @<Declare action...@>=
  21396. procedure fix_language;
  21397. var @!l:ASCII_code; {the new current language}
  21398. begin if language<=0 then l:=0
  21399. else if language>255 then l:=0
  21400. else l:=language;
  21401. if l<>clang then
  21402.   begin new_whatsit(language_node,small_node_size);
  21403.   what_lang(tail):=l; clang:=l;@/
  21404.   what_lhm(tail):=norm_min(left_hyphen_min);
  21405.   what_rhm(tail):=norm_min(right_hyphen_min);
  21406.   end;
  21407. @ @<Implement \.{\\setlanguage}@>=
  21408. if abs(mode)<>hmode then report_illegal_case
  21409. else begin new_whatsit(language_node,small_node_size);
  21410.   scan_int;
  21411.   if cur_val<=0 then clang:=0
  21412.   else if cur_val>255 then clang:=0
  21413.   else clang:=cur_val;
  21414.   what_lang(tail):=clang;
  21415.   what_lhm(tail):=norm_min(left_hyphen_min);
  21416.   what_rhm(tail):=norm_min(right_hyphen_min);
  21417.   end
  21418. @ @<Finish the extensions@>=
  21419. for k:=0 to 15 do if write_open[k] then a_close(write_file[k])
  21420. @* \[54] System-dependent changes.
  21421. This section should be replaced, if necessary, by any special
  21422. modifications of the program
  21423. that are necessary to make \TeX\ work at a particular installation.
  21424. It is usually best to design your change file so that all changes to
  21425. previous sections preserve the section numbering; then everybody's version
  21426. will be consistent with the published program. More extensive changes,
  21427. which introduce new sections, can be inserted here; then only the index
  21428. itself will get a new section number.
  21429. @^system dependencies@>
  21430. @* \[55] Index.
  21431. Here is where you can find all uses of each identifier in the program,
  21432. with underlined entries pointing to where the identifier was defined.
  21433. If the identifier is only one letter long, however, you get to see only
  21434. the underlined entries. {\sl All references are to section numbers instead of
  21435. page numbers.}
  21436. This index also lists error messages and other aspects of the program
  21437. that you might want to look up some day. For example, the entry
  21438. for ``system dependencies'' lists all sections that should receive
  21439. special attention from people who are installing \TeX\ in a new
  21440. operating environment. A list of various things that can't happen appears
  21441. under ``this can't happen''. Approximately 40 sections are listed under
  21442. ``inner loop''; these account for about 60\pct! of \TeX's running time,
  21443. exclusive of input and output.
  21444.